Java - Inheritance Method Overloading

Introduction

What is Method Overloading?

Creating more than one method with the same name in the same class is called method overloading.

Methods with the same name could be declared methods and inherited methods.

Overloaded methods must have different number of parameters, different types of parameters, or both.

The return type, access level and throws clause of a method are not part of the method signature and have no effect in overloaded method.

Example

The following class overload m1 method.

class MyClass {
        public void m1(int a) {
                // Code goes here
        }

        public void m1(int a, int b) {
                // Code goes here
        }

        public int m1(String a) {
                // Code goes here
        }

        public int m1(String a, int b) throws CheckedException1 {
                // Code goes here
        }
}

Method overloading is a kind of polymorphism where the same method name has different meanings.

Method overloading is bound at compile time.

Method overriding is bound at runtime.

The following code demonstrates How the Compiler Chooses the Most Specific Method from Several Versions of an Overloaded Method.

Demo

public class Main {
  public double add(int a, int b) {
    System.out.println("Inside add(int a, int b)");
    double s = a + b;
    return s;/*from w w  w  . ja  va  2  s.  co m*/
  }

  public double add(double a, double b) {
    System.out.println("Inside add(double a, double b)");
    double s = a + b;
    return s;
  }

  public void test(Employee e) {
    System.out.println("Inside test(Employee e)");
  }

  public void test(Manager e) {
    System.out.println("Inside test(Manager m)");
  }

  public static void main(String[] args) {
    Main ot = new Main();

    int i = 10;
    int j = 1;
    double d1 = 10.4;
    float f1 = 2.3F;
    float f2 = 4.5F;
    short s1 = 1;
    short s2 = 2;

    ot.add(i, j);
    ot.add(d1, j);
    ot.add(i, s1);
    ot.add(s1, s2);
    ot.add(f1, f2);
    ot.add(f1, s2);

    Employee emp = new Employee();
    Manager mgr = new Manager();
    ot.test(emp);
    ot.test(mgr);

    emp = mgr;
    ot.test(emp);
  }
}

class Employee {
}
class Manager extends Employee {
}

Result

Quiz