In Java, there are two ways to overload a method.
We have created an adding class with methods add(int, int) and add(int, int, int), i.e, we are overloading the methods by altering the number of arguments.
class Adding
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class Test{
public static void main(String[] args)
{
System.out.println(Adding.add(25,15));
System.out.println(Adding.add(11,15,19));
}
}
40
45
In this example, we have created an adding class with methods add(int, int) and add(String, String), note, that here the number of arguments is the same, but the data type of argument is different.
class Adding
{
static int add(int a,int b)
{
return a+b;
}
static String add(String a,String b)
{
return a+b;
}
}
class Test{
public static void main(String[] args)
{
System.out.println(Adding.add(25,15));
System.out.println(Adding.add("coder","zpy"));
}
}
40
coderzpy
Why is method overloading not possible simply by changing the method’s return type? Because of ambiguity, method overloading in Java is not possible by changing the method’s return type.
Can the main() method in Java be overloaded?
Yes, by method overloading. Method overloading allows you to have any number of main methods in a class. However, JVM calls the main() method, which only takes a string array as an argument.
// A Java program with overloaded main()
import java.io.*;
public class Test {
// Normal main()
public static void main(String[] args)
{
System.out.println("coderzpy (from main) 1");
Test.main("coderzpy!");
}
// Overloaded main methods
public static void main(String arg1)
{
System.out.println("Hi, " + arg1);
Test.main("coderpy ", "student");
}
public static void main(String arg1, String arg2)
{
System.out.println("Hi, " + arg1 + ", " + arg2);
}
}
coderzpy (from main) 1
Hi, coderzpy!
Hi, coderpy , student
Is Operator Overloading supported in Java?
Java does not support user-defined overloaded operators, unlike C++. Java overloads operators internally; for example, the + operator is overloaded for concatenation.
Note: also read about the Association, Composition & Aggregation in Java
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…