Advantage of Java Method Overriding:
1) Method Overriding is used to provide specific implementation of a method that is already provided by its super class.
2) Method Overriding is used for Runtime Polymorphism
Code Example:
In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.
class Engine{
void run(){System.out.println("Engine is running");}
}
class Car extends Engine{
void run(){System.out.println("Car is running Successfully ");}
public static void main(String args[]){
Car obj = new Car();
obj.run();
}
Output:
Car is running Successfully
1) Method Overriding is used to provide specific implementation of a method that is already provided by its super class.
2) Method Overriding is used for Runtime Polymorphism
Code Example:
In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.
class Engine{
void run(){System.out.println("Engine is running");}
}
class Car extends Engine{
void run(){System.out.println("Car is running Successfully ");}
public static void main(String args[]){
Car obj = new Car();
obj.run();
}
Output:
Car is running Successfully