Java Method Overriding in Java Inheritance

https:/‮‬/www.theitroad.com

In Java, method overriding is a feature of inheritance that allows a subclass to provide its own implementation of a method that is already defined in its superclass. When a subclass overrides a method, it provides a new implementation of that method that replaces the implementation inherited from the superclass.

To override a method in Java, you must define a method in the subclass with the same name, return type, and parameter list as the method in the superclass. You can then provide a new implementation of the method in the subclass. When a method is called on an object of the subclass, the new implementation in the subclass is called instead of the implementation inherited from the superclass.

Here's an example of method overriding in Java:

class Animal {
    public void speak() {
        System.out.println("I am an animal.");
    }
}

class Dog extends Animal {
    public void speak() {
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        myAnimal.speak(); // prints "I am an animal."
        
        Dog myDog = new Dog();
        myDog.speak(); // prints "Woof!"
    }
}

In the example above, the Dog class overrides the speak() method that is defined in its superclass, Animal. The Dog class provides its own implementation of the speak() method that prints "Woof!" instead of "I am an animal." When the speak() method is called on an object of the Dog class, the new implementation in the Dog class is called instead of the implementation inherited from the Animal class.

Method overriding is a powerful feature of inheritance in Java that allows you to provide specialized behavior in a subclass while still benefiting from the code reuse and polymorphism provided by inheritance. However, it's important to understand the implications of overriding methods, such as the potential for breaking existing code that depends on the behavior of the superclass implementation.