Method Overriding

When you override a method in a sub-class,

  • The overriding method must have the same signature (name and parameters) as the overridden one in the super-class.

  • In addition, it must have the same return type as the overridden one. Although, it could return a subtype of what is returned by the overridden method in the super-class.

  • Finally, it must be at least as visible as the overridden method. It is possible (yet strongly discouraged) to take a private or protected method and override it to a public one in a sub-class. The reverse is not possible; you can't override a public method to a protected or private one.

@Override annotation

When we override a method in a sub-class, 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 super-class.

  • 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 the method name, wrong ordering of parameters' types, etc.

You can learn more about Java annotations at Oracle's Java Tutorial: Annotations. However, we only use a few of these (primarily for unit testing) in this course.

Resources