ProgrammingJava Developer

How does the method overriding mechanism work in Java, how to use it correctly and what nuances should be considered?

Pass interviews with Hintsage AI assistant

Answer.

Method overriding is an OOP mechanism where a subclass provides its own implementation of a method that is already defined in its superclass. The method in the subclass must have the same name, parameters, and return type (or be a subtype of it).

Key rules:

  • Methods must be public or protected (not more restrictive access level).
  • You cannot override private and static methods.
  • Using the @Override annotation helps catch errors at compile time.
  • Java supports covariant return type (the overridden method can return a subtype of the original return type).
  • Exceptions: the method in the subclass cannot declare new checked exceptions that are not in the signature of the base method.

Example:

class Animal { public void sound() { System.out.println("Some sound"); } } class Dog extends Animal { @Override public void sound() { System.out.println("Woof"); } }

Trick question.

Question: "Can a static method be overridden in Java?"

Answer: No, static methods cannot be overridden. They are hidden (method hiding). If a static method with the same signature is declared in the subclass, hiding occurs instead of overriding.

Example:

class A { static void print() { System.out.println("A"); } } class B extends A { static void print() { System.out.println("B"); } } A obj = new B(); obj.print(); // prints "A"

Examples of real errors due to lack of knowledge about the nuances of the topic.


Story

On a project, one of the developers tried to "override" a static method in the inherited class, expecting to call the version from the subclass through the superclass reference. This led to unexpected results: the superclass method was called, causing the program to behave incorrectly.


Story

It is important to use the @Override annotation. In one project, a developer made a mistake in the method name during overriding, and without the annotation, the compiler did not throw an error. As a result, the method of the base class was called by default, which caused incorrect logic in business processes.


Story

Overriding checked exceptions: a developer added throwing a new checked exception in the overridden method that was not specified in the original signature. The code compiled with an error, and it was necessary to change the architecture as it violated the rule of exception overriding.