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:
@Override annotation helps catch errors at compile time.Example:
class Animal { public void sound() { System.out.println("Some sound"); } } class Dog extends Animal { @Override public void sound() { System.out.println("Woof"); } }
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"
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
@Overrideannotation. 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.