In this tutorial, we will see the method overriding in Java.
When a child class provides a specific implementation for the method already declared in parent class, it is called a method overriding.
So both parent class and child class will have the same method but with different implementations.
Example:-
/**
* A Java Program to explain the method of overriding.
* @author coderolls.com
*
*/
public class Test {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.printSound();
cat.printSound();
}
}
class Animal {
public void printSound() {
System.out.println("Print sound of animal");
}
}
class Dog extends Animal {
@Override
public void printSound() {
System.out.println("Dogs bark..!");
}
}
class Cat extends Animal {
@Override
public void printSound() {
System.out.println("Cats meow..!");
}
}
- In the above example
Animalis the parent class. It has theprintSound()method with its own implementation. - Next, we have created a child class
Dogby extending the parent classAnimal. We know dogs do bark so we can provide the specific implementation for theprintSound()method in theDogclass. - Also, we have created a child class
Catby extending the parent classAnimal. We can again provide the cat-specific implementation for theprintSound()method in theCatclass. - In the Test class, we have created objects of the Dog and Cat class and invoked their
printSound()method. We can see, that when we invoke theprintSound()method on Dog objectdog, it prints theDogs bark..!i.e. dog specific implementation. And when we invoke theprintSound()method on the Cat objectcat, it prints theCats meow..!i.e. dog specific implementation