Java - Inheritance Method Overriding

What is Method Overriding.

Redefining an instance method inherited from the superclass is called method overriding.

Example

Consider the following declarations:

class A {
        public void print() {
                System.out.println("A");
        }
}

class B extends A {
        public void print() {
                System.out.println("B");
        }
}

Class B is a subclass of class A.

Class B inherits the print() method from A and redefines it.

print() method in class B overrides the print() method of class A.

Overriding a method affects the overriding class and its subclasses.

public class C extends B {
        // Inherits B.print()
}

class inherits what is available from its immediate superclass.

Rule

Here are the rules for overriding a method.

  • Overriding does not apply to static methods.
  • Overriding method must have the same name as the overridden method.
  • Overriding method must have the same number of parameters in the same order as the overridden method.
  • Return type of the overriding and the overridden methods must be the same for primitive types.
  • If the return type of the overridden method is a reference type, the return type of the overriding method must be assignment compatible to the return type of the overridden method.
  • The access level of the overriding method must be at least the same or more relaxed than that of the overridden method.
  • The overriding method cannot add a new exception to the list of exceptions in the overridden method.

Access Level

List of Allowed Access Levels for an Overriding Method

Overridden Method Access LevelAllowed Overriding Method Access Level
publicpublic
protected public, protected
package-level public, protected, package-level

Summary

To summarize the rules of overriding

Item Rule
Name of the method must always be the same in the overriding and the overridden methods
Number of parameters must always be the same in the overriding and the overridden methods
Type of parameters must always be the same in the overriding and the overridden methods
Order of parametersmust always be the same in the overriding and the overridden methods
Return type of parameters overriding a method's return type could also be a subtype (any descendant) of the return type of the overridden method.
Access levelAn overriding method may relax the constraints of the overridden method.
List of checked exceptions in the throws clauseAn overriding method may relax the constraints of the overridden method.

Related Topics