DEV Community

Deva I
Deva I

Posted on

Method Overloading in Java

=> 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);

  }
}
Enter fullscreen mode Exit fullscreen mode

3 Ways to Overload a Method

  1. Number of parameters.

  2. Data types of parameters.

  3. Order of parameters.

  • Number of parameters: Having a different count of inputs.
 casio.add(10,5);
 casio.add(1000);
 casio.add(3,3,3);
Enter fullscreen mode Exit fullscreen mode
// One integer and add 500

 public void add(int i){
  System.out.println(i+500);

  }
Enter fullscreen mode Exit fullscreen mode

  // Add two integer, two different parameters

  public void add(int i, int j){
  System.out.println(i+j);

  }
Enter fullscreen mode Exit fullscreen mode
  // 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);

  }
Enter fullscreen mode Exit fullscreen mode
  • Data types of parameters: Having the same count but different variable types((e.g., int vs float)
casio.add(10.5f,9.5f);
Enter fullscreen mode Exit fullscreen mode
public void add( float i, float j){
  System.out.println(i+j);

  }

Enter fullscreen mode Exit fullscreen mode
  • widening conversion
 casio.add('a');
Enter fullscreen mode Exit fullscreen mode
   public void add(int i){
  System.out.println(i+500);

  }
Enter fullscreen mode Exit fullscreen mode

=> 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.

Output

Top comments (0)