![]() |
VOOZH | about |
Method overriding in Java allows a subclass to provide a specific implementation of a method that is already defined in its parent class. It is one of the key features of runtime polymorphism in object-oriented programming.
Dog is running. Animal is eating. Dog is barking.
Explanation: The Animal class defines base functionalities like move() and eat(). The Dog class inherits from Animal and overrides the move() method to provide a specific behavior Dog is running. Both classes can access their own methods. When creating a Dog object, calling move() executes the overridden method.
The super keyword can invoke the parent class method from the overriding method.
Parent's show() Child's show()
If we don't want a method to be overridden, we declare it as final. Please see Using Final with Inheritance.
Output:
Parent static method Child instance method
Child method
Child object
Child method
Let’s understand overriding with a real-world analogy.
Imagine an organization’s Employee Management System. All employees share some behaviors like raiseSalary() and promote(), but the logic differs for different roles like Manager or Engineer. We can create a single Employee array where individual employees are of different types (sales, tech, etc) and call their functions. This simplifies the overall code a lot.
--- Raising Salaries --- Manager salary raised with incentives. Engineer salary raised with bonus. --- Promotions --- Manager promoted to Senior Manager. Engineer promoted to Senior Engineer.
Explanation: Although both Manager and Engineer objects are referred to using the Employee type, Java calls the overridden methods of the actual objects at runtime, demonstrating dynamic method dispatch (runtime polymorphism).
Related Article: Method Overloading and Method Overriding