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 or protected method and override it to a public one in a subclass, 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 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