Java Concepts‎ > ‎

Overloading vs. overriding

Method overloading occurs when two or more methods have the same name but different signatures (that is, different parameter lists).
public void DisplaySum(int x, int y) {
    System.out.println(x + y);
}
public void DisplaySum(double x, double y) {
    System.out.println(x + y);
} 
Note: When we call an overloaded method (for example, DisplaySum(num1, num2)), the compiler should compare both methods signatures and bind the call to the method whose parameter data types match the data types of the arguments passed. 

The method overloading can take place in the same class or where the methods are located both in the superclass and the subclass. A subclass method overloads a superclass method; however, both methods are accessible as the subclass methods.

Method overriding occurs when two methods (a subclass method and a superclass method) both have the same signature. Let us look at the following two toString() methods. The first one is located in a superclass and the second one is located in a subclass:

public String toString() {
    return "Object{" + "name=" + name + "price=" + price + '}'
}

public String toString() {
    return "Object{" + "name=" + super.getName + "price=" +  super.getPrice
        +
"address=" + address + "type=" + type + '}';
}

Note: When a subclass method has the same signature as a superclass method, the subclass method is executed and the superclass method is ignored by compiler.

The method overriding can take place only when the methods are located in the superclass and the subclass. A subclass method overrides a superclass method; therefore, only the subclass method is accessible. In this case, to access the superclass method we should use the super keyword in the method call: super.method().
Comments