Method Overriding in Java
If child class has the same method which is declared in the parent class, it is known as method overriding in java.
Method overriding provides specific implementation of a method which is already provided by its parent class.
The implementation in the child class overrides the implementation in the parent class and this method has same name, same parameters or signature, and same return type as the method in the parent class.
Case without Method overriding
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}
}
OUTPUT
Vehicle is running
Case with Method overriding
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}
OUTPUT
Bike is running safely
0 Comment(s)