Method overriding is a feature in Java that allows a subclass to provide its own implementation of a method that is already defined in its superclass. The subclass method must have the same name, return type, and parameters as the superclass method.
When a method in a subclass has the same name and signature as a method in its superclass, the subclass method overrides the superclass method. The process of choosing the most specific implementation of a method at runtime is called dynamic method dispatch.
Here is an example of method overriding:
public class Animal {
public void speak() {
System.out.println("Animal speaks");
}
}
public class Dog extends Animal {
@Override
public void speak() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.speak(); // output: Animal speaks
Dog dog = new Dog();
dog.speak(); // output: Dog barks
Animal anotherDog = new Dog();
anotherDog.speak(); // output: Dog barks
}
}
In this example, we have a superclass Animal
with a method speak()
. We also have a subclass Dog
that extends Animal
and overrides the speak()
method. When we create an instance of Dog
, we can call its speak()
method to get the overridden behavior.
It’s important to note that the @Override
annotation is used in the subclass method to indicate that it is overriding a method in the superclass. This is not strictly necessary, but it can help prevent errors if the method signature in the superclass changes.