A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding .
The toString method in the GeometricObject class returns the string representation for a geometric object. This method can be overridden to return the string representation for a circle. To override it, add the following new method in Listing 9.2, Circle.java:
public class Circle extends GeometricObject { // Other methods are omitted /** Override the toString method defined in GeometricObject */ public String toString() { return super .toString() + "\nradius is " + radius; } }
The toString() method is defined in the GeometricObeject class and modified in the Circle class. Both methods can be used in the Circle class. To invoke the toString method defined in the GeometricObject class, use super.toString() . Can a subclass of Circle access the toString method defined in the GeometricObject class using a syntax such as super.super.toString() ? No. This is a syntax error. Can an instance of Circle invoke the toString method defined in the GeometricObject class? No, not any more, since toString() in GeometricObject has been overridden in Circle .
Note
Private data fields and methods in a superclass are not accessible outside of the class. Therefore, they are not inherited in a subclass. |
Note
An instance method can be overridden only if it is accessible. Thus a private method cannot be overridden, because it is not accessible outside its own class. If a method defined in a subclass is private in its superclass, the two methods are completely unrelated. |
Note
Like an instance method, a static method can be inherited. However, a static method cannot be overridden. If a static method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden. Hiding static methods will be further discussed in §9.14, "Hiding Data Fields and Static Methods." |