Method overriding in Java
Source: Dev.to
What is method overriding
When a subclass provides a specific implementation for a method that is already defined in its parent class, it is called method overriding.
The overridden method in the subclass must have the same name, parameters, and return type as the method in the parent class.
Rules for method overriding
- Static methods cannot be overridden. Defining a static method in a subclass with the same signature as in the superclass hides the superclass method.
- Instance methods can be overridden, but a subclass cannot override a superclass static method.
- A static method in a subclass with the same signature as a superclass static method hides the original method.
- Private methods cannot be overridden because they are not visible to subclasses.
- A subclass method with the same name (when the superclass method is private) is treated as a new, independent method, unrelated to the parent class.