Curriculum
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 can define a method with the same name, return type, and parameter list as the method in its superclass, but with a different implementation. When the method is called on an object of the subclass, the subclass’s implementation is executed instead of the superclass’s implementation.
Here is an example that illustrates method overriding in Java:
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound(); // Output: The animal makes a sound
Dog dog = new Dog();
dog.makeSound(); // Output: The dog barks
Animal animal1 = new Dog();
animal1.makeSound(); // Output: The dog barks
}
}
In this example, we have a superclass Animal with a method makeSound(), which prints “The animal makes a sound”. We then have a subclass Dog that extends Animal, and overrides the makeSound() method with its own implementation, which prints “The dog barks”.
In the main() method, we first create an Animal object and call its makeSound() method, which prints “The animal makes a sound”. We then create a Dog object and call its makeSound() method, which prints “The dog barks”. Finally, we create an Animal object and assign it a reference to a Dog object, and call its makeSound() method, which still prints “The dog barks” because the makeSound() method is overridden in the Dog class and the type of the reference doesn’t affect which implementation of the method is called.