Overloading means to define multiple methods with the same name but different signatures. Overriding means to provide a new implementation for a method in the subclass. To override a method, the method must be defined in the subclass using the same signature and the same return type.
Let us use an example to show the differences between overriding and overloading. In (a) below, the method p(double i) in class A overrides the same method defined in class B. In (b), however, the class A has two overloaded methods: p(double i) and p(int i). The method p(double i) is inherited from B.
When you run the Test class in (a), both a.p(10) and a.p(10.0) invoke the p(double i) method defined in class A to display 10.0. When you run the Test class in (b), a.p(10) invokes the p(int i) method defined in class A to display 10, and a.p(10.0) invokes the p(double i) method defined in class B to display 20.0.
Note the following:
- Overridden methods are in different classes related by inheritance; overloaded methods can be either in the same class or different classes related by inheritance.
- Overridden methods have the same signature and return type; overloaded methods have the same name but a different parameter list.
To avoid mistakes, you can use a special Java syntax, called override annotation, to place @override before the method in the subclass. For example:
public class CircleFromSimpleGeometricObject
extends SimpleGeometricObject {
// Other methods are omitted
@Override
public String toString() {
return super.toString() + "\nradius is " + radius;
}
}
This annotation denotes that the annotated method is required to override a method in the superclass. If a method with this annotation does not override its superclass’s method, the compiler will report an error. For example, if toString is mistyped as tostring, a compile error is reported. If the override annotation isn’t used, the compile won’t report an error. Using annotation avoids mistakes.
Top comments (0)