Method Overriding

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

  • Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
  • Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.
  3. There must be an IS-A relationship (inheritance).
  1. //Creating a parent class  
  2. class Vehicle{  
  3.   void run(){System.out.println(“Vehicle is running”);}  
  4. }  
  5. //Creating a child class  
  6. class Bike extends Vehicle{  
  7.   public static void main(String args[]){  
  8.   //creating an instance of child class  
  9.   Bike obj = new Bike();  
  10.   //calling the method with child class instance  
  11.   obj.run();  
  12.   }  
  13. }  

Leave a comment

Design a site like this with WordPress.com
Get started