If we have methods with same signature (same name, same signature, same return type) in super class and subclass then we say subclass method is overridden by super-class.
When to use overriding in java.
If we want same method with different behavior in super-class and subclass then we go for overriding.
When we call overridden method with subclass reference subclass method is called hiding the super-class method.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//Java Program to illustrate the use of Java Method Overriding //Creating a parent class. class Vehicle { //defining a method void run() { System.out.println("Vehicle is running"); } } //Creating a child class class Car extends Vehicle { //defining the same method as in the parent class void run() { System.out.println("Car is running safely"); } public static void main(String args[]) { Bike2 obj = new Car(); //creating object obj.run(); //calling method } } |
Output:-
1 |
Car is running safely |