Redefining an instance method inherited from the superclass is called method overriding.
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.
Here are the rules for overriding a method.
List of Allowed Access Levels for an Overriding Method
Overridden Method Access Level | Allowed Overriding Method Access Level |
---|---|
public | public |
protected | public, protected |
package-level | public, protected, package-level |
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 parameters | must 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 level | An overriding method may relax the constraints of the overridden method. |
List of checked exceptions in the throws clause | An overriding method may relax the constraints of the overridden method. |