Method Overriding in Java

 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).

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 are the same, and there is IS-A relationship between the classes, so there is method overriding.

  • //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 Bike2 extends Vehicle{  
  •   //defining the same method as in the parent class  
  •   void run(){System.out.println("Bike is running safely");}  
  •   
  •   public static void main(String args[]){  
  •   Bike2 obj = new Bike2();//creating object  
  •   obj.run();//calling method  
  •   }  
  • }  

Output:

Bike is running safely

The End

No comments:

Post a Comment

Aarsh Prajapati

Welcome! Java Programs And Theory  Practical    Theory Java Basic Program Java Simple Program Array, Inheritance and Interface Program Packa...