|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: "Method Overriding In Java" |
| 4 | +author: gaurav |
| 5 | +categories: [Java, Java Interview Questions] |
| 6 | +toc: false |
| 7 | +description: "In this tutorial, we will see the method overriding in Java." |
| 8 | +--- |
| 9 | + |
| 10 | +In this tutorial, we will see the method overriding in Java. |
| 11 | + |
| 12 | +When **a child class provides a specific implementation for the method already declared in parent class**, it is called a method overriding. |
| 13 | + |
| 14 | +So both parent class and child class will have the same method but with different implementation. |
| 15 | + |
| 16 | +Example:- |
| 17 | + |
| 18 | +```java |
| 19 | +/** |
| 20 | + * A Java Program to explain method oeverriding. |
| 21 | + * @author coderolls.com |
| 22 | + * |
| 23 | + */ |
| 24 | +public class Test { |
| 25 | + public static void main(String[] args) { |
| 26 | + Dog dog = new Dog(); |
| 27 | + Cat cat = new Cat(); |
| 28 | + |
| 29 | + dog.printSound(); |
| 30 | + cat.printSound(); |
| 31 | + } |
| 32 | + |
| 33 | +} |
| 34 | +class Animal { |
| 35 | + |
| 36 | + public void printSound() { |
| 37 | + System.out.println("Print sound of animal"); |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +class Dog extends Animal { |
| 42 | + |
| 43 | + @Override |
| 44 | + public void printSound() { |
| 45 | + System.out.println("Dogs bark..!"); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +class Cat extends Animal { |
| 50 | + |
| 51 | + @Override |
| 52 | + public void printSound() { |
| 53 | + System.out.println("Cats meow..!"); |
| 54 | + } |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +1. In above example `Animal` is the parent class. It has `printSound()` method with it's own implementation. |
| 59 | +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. |
| 60 | +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. |
| 61 | +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 `d`og, 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 |
0 commit comments