Method Overriding in Java

Method Overriding in Java


In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.

Usage of Java Method Overriding

  • Method overriding is used to provide specific implementation of a method that is already provided by its super class.
  • Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

  1. method must have same name as in the parent class
  2. method must have same parameter as in the parent class.
  3. must be IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.
  1. class Vehicle{  
  2.   void run()
  3. {
  4. System.out.println("Vehicle is running");
  5. }  
  6. }  
  7. class Bike extends Vehicle{  
  8.     
  9.   public static void main(String args[]){  
  10.   Bike obj = new Bike();  
  11.   obj.run();  
  12.   }  
  13. }  

Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.

Example of method overriding

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.

  1. class Vehicle{  
  2. void run()
  3. {
  4. System.out.println("Vehicle is running");
  5. }  
  6. }  
  7. class Bike2 extends Vehicle
  8. {  
  9. void run()
  10. {
  11. System.out.println("Bike is running safely");
  12. }  
  13.   
  14. public static void main(String args[]){  
  15. Bike2 obj = new Bike2();  
  16. obj.run();  
  17. }  

Output:Bike is running safely

Previous
Next Post »