Method overriding is a feature of Java 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, which replaces the implementation inherited from the superclass. The new implementation in the subclass must have the same method signature (name, return type, and parameter list) as the method being overridden in the superclass.
Here's an example of method overriding in Java:
class Animal {
void makeSound() {
System.out.println("The animal makes a sound.");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("The cat meows.");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
myAnimal.makeSound(); // Output: "The animal makes a sound."
Cat myCat = new Cat();
myCat.makeSound(); // Output: "The cat meows."
}
}
In this example, the Animal class has a makeSound() method that simply prints out a message. The Cat class extends the Animal class and overrides the makeSound() method with its own implementation that prints out "The cat meows."
When the makeSound() method is called on an instance of the Animal class, the output is "The animal makes a sound." However, when the same method is called on an instance of the Cat class, the output is "The cat meows." This is because the Cat class has provided its own implementation of the makeSound() method, which overrides the implementation inherited from the Animal class.