Gaurav Kukade
Gaurav Kukade Hi ๐Ÿ‘‹๐Ÿผ I'm Gaurav Kukade, a software developer. I write tutorials for Java programming language and related technologies.

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..!");
    }
}
  1. In above example Animal is the parent class. It has printSound() method with itโ€™s own implementation.
  2. Next, we have created a child class Dog by extending the parent class Animal. We know dogs do bark so we can provide specific implementation for the printSound() method in Dog class.
  3. Also, we have created a child class Cat by extending the parent class Animal. We can again provide cat specific implementation for the printSound() method in Cat class.
  4. In Test class, we have created objects of Dog and Cat class and invoked their printSound() method. We can see, when we invoke the printSound() method on Dog obejct dog, it is printing the Dogs bark..! i.e. dog specific implementation. And when we invoke the printSound() method on Cat obejct cat, it is printing the Cats meow..! i.e. dog specific implementation
Join Newsletter
Get the latest tutorials right in your inbox. We never spam!

comments powered by Disqus