=> Method Overloading in Java allows a class to have same method name with different number of arguments or with type of arguments.
=> It is a core concept of oop used to achieve compile-time polymorphism.
=> Compile-time polymorphism means the Java compiler determines exactly which method to execute during compilation based on the method signature.
Code Example
public class Calculator
{
public static void main(String[] args)
{
Calculator casio= new Calculator();
casio.add(10,5);
casio.add(1000);
casio.add(3,3,3);
casio.add(10.5f,9.5f);
casio.add('a');
}
public void add(int i){
System.out.println(i+500);
}
public void add(int i, int j){
System.out.println(i+j);
}
public void add(int i, int j, int k){
System.out.println(i*j*k);
}
public void add( float i, float j){
System.out.println(i+j);
}
}
3 Ways to Overload a Method
Number of parameters.
Data types of parameters.
Order of parameters.
- Number of parameters: Having a different count of inputs.
casio.add(10,5);
casio.add(1000);
casio.add(3,3,3);
// One integer and add 500
public void add(int i){
System.out.println(i+500);
}
// Add two integer, two different parameters
public void add(int i, int j){
System.out.println(i+j);
}
// Add three integers, three different parameters in one method 'add'
public void add(int i, int j, int k){
System.out.println(i*j*k);
}
- Data types of parameters: Having the same count but different variable types((e.g.,
intvsfloat)
casio.add(10.5f,9.5f);
public void add( float i, float j){
System.out.println(i+j);
}
- widening conversion
casio.add('a');
public void add(int i){
System.out.println(i+500);
}
=> A char can be automatically type converted to an int.
=> The character 'a' has the Unicode/ASCII value = 97.
=> (i+500).i is 97+500 = 597.

Top comments (0)