Method Overloading in Java

When two or more then two methods sharing same name within the same class, having different type of parameters or different number of parameters. This is known as method overloading.

public class MethodOverload {

 public static void main(String[] args) {
    System.out.println("The sum of 10 and 20 " + sum(10, 20));
    System.out.println("The sum of 10.0 and 10.4 is " + sum(10.0, 10.4));
    System.out.println("The sum of 3.0, 5.4, and 10.14 is " + sum(3.0, 5.4, 10.14)); }
   
 public static int sum(int num1, int num2) {
  return num1+num2;
}

public static double sum(double num1, double num2) {
 return num1+num2;
}

public static double sum(double num1, double num2, double num3) {
  return sum(sum(num1, num2), num3); }
}

Ambiguous Invocation

It’s possible that there are two or more possible matches for a method invocation where compiler unable to determine the most specific choice. This is known as ambiguous invocation and cause compilation error.

public class AmbiguousMethod {

 public static void main(String[] args) {
   System.out.println("The sum of 10 and 20 " + sum(10, 20));
}
 public static int sum(int num1, double num2) {
  return num1+num2;
}
 public static double sum(double num1, int num2) {
  return num1+num2;
}
}

 

Comments

  1. Reply

    • By Gul

      Reply

  2. Reply

    • By Gul

      Reply

  3. Reply

  4. Reply

  5. Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.