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 implementation.
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
35
36
37
/**
* A Java Program to explain method oeverriding.
* @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 above example
Animal
is the parent class. It hasprintSound()
method with itโs own implementation. - Next, we have created a child class
Dog
by extending the parent classAnimal
. We know dogs do bark so we can provide specific implementation for theprintSound()
method inDog
class. - Also, we have created a child class
Cat
by extending the parent classAnimal
. We can again provide cat specific implementation for theprintSound()
method inCat
class. - In Test class, we have created objects of Dog and Cat class and invoked their
printSound()
method. We can see, when we invoke theprintSound()
method on Dog obejctd
og, it is printing theDogs bark..!
i.e. dog specific implementation. And when we invoke theprintSound()
method on Cat obejctcat
, it is printing theCats meow..!
i.e. dog specific implementation
Join Newsletter
Get the latest tutorials right in your inbox. We never spam!