5 Minutes of Java (13. Method Overloading vs Method Overriding)

Method overloading and method overriding are two completely different concepts. To distinguish the two, we need to first understand method signature.

Method signature consists of both method name and parameter list, if two methods have the same name and the same parameter list, then they have the same method signature.

public class SampleClass{

  public void drawA() {}

  public void drawA(int i) {}

  public int drawB() {}

  public void drawB() {}

  public void drawC(int m) {System.out.println(m);}

  public void drawC(int n) {System.out.println(n);}
}

From the example given above, two drawA methods have the same method name but different parameter list (one has no parameter, the other has one of type int), so they have different method signatures. However,  two drawB methods have the same method signature since they have the same method method and parameter list though they have different return types (one returns int and the other returns nothing). Similarly, two drawC methods also have the same method signature though the variable names used for parameters are different (one uses m and the other uses n). Java does not allow two methods of the same signature defined within the same class, so in our case, drawB and drawC would give compilation errors.

Now we can go on to talk about method overloading and overriding. Method overloading happens when we have two or more methods with the same name but different parameter lists within a class. In our earlier example, method overloading occurs for two drawA methods.

For method overriding, we must have at least one superclass and one subclass. It occurs when one method in the subclass has the same signature as one method inherited from its superclass.

public class Parent {
  public void show() {
    System.out.println("Parent class");
  }
}
public class Child extends Parent{
  public void show() {
    System.out.println("Child class - method overriding");
  }
}

In the example given above, the show method in the superclass is overridden in the subclass.

In this case, if we call show method in Child class, it would display “Child class -method overriding”, if we want to call show method in its superclass, we need to call super.show().

To summarize,

  Within same class? Same name? Same parameter list?
Overloading Yes* Yes No
Overriding No (one in subclass, one in superclass) Yes Yes

*Note: method overloading could also happen in subclass when it inherits a method with the same name but different parameter list from its superclass, like the example given below.

public class Parent {
 public void show() {
 System.out.println("Parent class");
 }
}
public class Child extends Parent{
 public void show(int i) {
 System.out.println("Child class - method overloading");
 }
}

For more details on method overloading and method overriding, you can look at this link: method overriding vs overloading