DEV Community

Cover image for Overriding Methods
Paul Ngugi
Paul Ngugi

Posted on

Overriding Methods

To override a method, the method must be defined in the subclass using the same signature and the same return type as in its superclass. 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 (lines 46–48 in SimpleGeometricObject.java, here) returns the string representation of a geometric object. This method can be overridden to return the string representation of a circle. To override it, add the following new method in the Circle class in CircleFromSimpleGeometricObject.java, here.

 public class CircleFromSimpleGeometricObject
 extends SimpleGeometricObject {
 // Other methods are omitted

 // Override the toString method defined in the superclass
 public String toString() {
 return super.toString() + "\nradius is " + radius;
 }
 }
Enter fullscreen mode Exit fullscreen mode

The toString() method is defined in the GeometricObject 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 from the Circle class, use super.toString() (line 7).

Can a subclass of Circle access the toString method defined in the GeometricObject class using syntax such as super.super.toString()? No. This is a syntax error.

Several points are worth noting:

  • 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.
  • 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. The hidden static methods can be invoked using the syntax SuperClassName.staticMethodName.

Top comments (0)