Method Overriding in Java

Method Overriding is a feature in Java that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This enables polymorphism, where a call to an overridden method is resolved at runtime, allowing for dynamic method dispatch.

Key Points on Method Overriding:

Syntax of Method Overriding:

Syntax Example

class Superclass {
            void display() {
                // Superclass method implementation
            }
        }
        
        class Subclass extends Superclass {
            @Override
            void display() {
                // Overridden method implementation
            }
        }

Example of Method Overriding in Java:

This example demonstrates how method overriding works by defining a superclass and a subclass with an overridden method.

Code Example: Method Overriding

class Animal {
            void sound() {
                System.out.println("Animal makes a sound");
            }
        }
        
        class Dog extends Animal {
            @Override
            void sound() {
                System.out.println("Dog barks");
            }
        }
        
        class Cat extends Animal {
            @Override
            void sound() {
                System.out.println("Cat meows");
            }
        }
        
        public class TestOverriding {
            public static void main(String[] args) {
                Animal myAnimal;  // Declare an Animal reference
                myAnimal = new Dog();  // Instantiate Dog
                myAnimal.sound();  // Calls Dog's sound method
                
                myAnimal = new Cat();  // Instantiate Cat
                myAnimal.sound();  // Calls Cat's sound method
            }
        }

Output

Dog barks
Cat meows

Detailed Explanation:

By utilizing method overriding, developers can create a more flexible and dynamic system that adheres to the principles of object-oriented programming, ultimately leading to better-organized code and increased reusability.