Method Overloading in Java

In Java, we can have two or more methods with same name if they have different parameters.

Different parameters means if they have

  • different numbers of parameters (or)
  • different data types of parameters (or)
  • both

If you remember constructor overloading, then it is same here.

Method overloading helps us to increase redability of a program.


Examples:


By changing number of parameters

See the example below where we have same method but different number of parameters.

public class LearnMethodOverloading { public static void main(String[] args) { LearnMethodOverloading lmo = new LearnMethodOverloading(); lmo.display(); lmo.display(5); lmo.display(5, 3); } void display() { System.out.println("I am blank."); } void display(int x) { System.out.println("I am with " + x); } void display(int x, int y) { System.out.println("I am with " + x + " and " + y); } }
Here we have three display method but different parameters for each method. It will print:
I am blank.
I am with 5
I am with 5 and 3


By changing data type of parameters

See the example below where we have same method but different data type of parameters.

public class LearnMethodOverloading { public static void main(String[] args) { LearnMethodOverloading lmo = new LearnMethodOverloading(); lmo.display(3, 5); lmo.display(5.5, 3.2); } void display(int x, int y) { System.out.println("Integer: " + (x+y)); } void display(double x, double y) { System.out.println("Double: " + (x+y)); } }
Here we have three display method but different data type of parameters. It will print:
Integer: 8
Double: 8.7


this keyword in Java Previous Next Recursion in Java