Method Overriding
When you override a method in a subclass, the overriding method must
- have the same signature (name and parameters) as the overridden one in the superclass.
- have the same return type as the overridden one (or it must return a subtype of what is returned by the overridden method in the superclass).
- be at least as visible as the overridden method. (It is possible [yet strongly discouraged] to take a
private
orprotected
method and override it to apublic
one in a subclass, the reverse is not possible; you can't override apublic
method to aprotected
orprivate
one.)
@Override
annotation
When we override a method in a subclass, we annotate it with @Override
annotation.
Annotations in Java are meta data: they provide data about a program but they are not part of the program itself.
Annotations have no direct effect on the operation of the code they annotate. That said, using @Override
annotation is considered a good programming practice and you must follow it (at least in this course) because of the following advantages:
-
It improves the readability of the code; it indicates that a method declaration is intended to override a method in a superclass.
-
If the annotation is used, the Java compiler will double-check the method signature and report an error if there is any mismatch. This feature prevents unintended mistakes such as: misspelling of the method name, wrong ordering of parameters' types, etc.
You can learn more about Java annotations at Oracle's Java Tutorial: Annotations. We only use a few of these (mostly for unit testing) in this course.
Resources
- JavaPractices Overridable methods need special care.
- JavaPractices Use @Override liberally.