Computer >> Computer tutorials >  >> Programming >> Java

Method overloading in Java


Method overloading is a type of static polymorphism. In Method overloading, we can define multiple methods with the same name but with different parameters. Consider the following example program.

Example

public class Tester {
   public static void main(String args[]) {
      Tester tester = new Tester();
      System.out.println(tester.add(1, 2));
      System.out.println(tester.add(1, 2,3));
   }
   public int add(int a, int b) {
      return a + b;
   }
   public int add(int a, int b, int c) {
      return a + b + c;
   }
}

Output

3
6

Here we’ve used a method add() which can take either two or three parameters and can acts accordingly. This is called method overloading or static polymorphism.