DEV Community

VIDHYA VARSHINI
VIDHYA VARSHINI

Posted on

Method Overloading in Java

What is method overloading: This is defined as a feature that allows a class to have multiple methods with the same name but different parameters. It is also known as compile time polymorphism.
Methods can share the same name if their parameter lists differ.

The different ways of method overloading in Java are given as :

  1. Changing the number of parameters
  2. Changing the data types of parameters
  3. Changing the order of parameters

Ex:

class Calculator{
public static void main(String[] args) {
Calculator casio = new Calculator();
casio.add(10,20);
casio.add(10,20,30);
casio.add("Sun","Flower");
casio.add(10,"abc");
}

public void add(int no1, int no2){        
System.out.println(no1+no2);
}

public void add(int no1, int no2, int no3){  
System.out.println(no1+no2+no3);
}

public void add(String name1, String name2){
System.out.println(name1 + name2);
}

public void add(int no1, String name){
System.out.println(no1+name);
}
}
Enter fullscreen mode Exit fullscreen mode

Output:

30
60
SunFlower
10abc

Enter fullscreen mode Exit fullscreen mode

In the above code, the first two methods have different number of arguments (2 and 3). The third method accepts two String parameters. The last method uses two parameters of different types (int and String).

Polymorphism: It is a core concept of Object-Oriented Programming (OOPs) that allows a single action to be performed in different ways. This is derived from a Greek word where "poly" means many and "morphs" means forms which simply denotes many forms or many methods. This can be further classified into two types:

a. Compile time polymorphism : It occurs when a class has multiple methods with the same name but different parameters (number of parameters, type of parameters, or order of parameters).

b. Run time polymorphism : It occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The decision of which method to execute is made at runtime, based on the actual object type being referenced.

Why method overloading is called as compile time polymorphism:
• Method overloading is called compile-time polymorphism because the compiler decides which overloaded method to call before the program runs.
• When we have multiple methods with same name but different types or number of arguments, the compiler checks the method signature and decides which version of the method to call.
• This happens during compilation, not at runtime.
• Overloading does not depend on object type or inheritance. The compiler just matches the best method signature.

Top comments (0)