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.
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…