Method Overriding In Java
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:-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 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
Animal
is the parent class. It has theprintSound()
method with its own implementation. - Next, we have created a child class
Dog
by extending the parent classAnimal
. We know dogs do bark so we can provide the specific implementation for theprintSound()
method in theDog
class. - Also, we have created a child class
Cat
by extending the parent classAnimal
. We can again provide the cat-specific implementation for theprintSound()
method in theCat
class. - 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
Join Newsletter
Get the latest tutorials right in your inbox. We never spam!