Method Overriding in Java

If subclass has the same method as declared in the super class, it is known as method overriding in Java. It is required in the case, when we want to use the implementation of the child class instead of parent class.

Usage of Java Method Overriding

  • Method overriding is used to provide the specific implementation of a method in the child class which is already provided by its parent class.
  • Runtime polymorphism is used through method overriding.

Rules for Java Method Overriding

  • The method in the subclass must have the same name as in the super class.
  • The method must have the same parameter as in the parent class.
  • There must be an IS-A relationship (inheritance concept must be used).

Example of method overriding

 

//Java Program understand the use of Method Overriding 

// parent class. 

class Vehicle{ 

  //defining a method 

  void run(){System.out.println("Vehicle is running");} 

} 

// child class 

class Bike 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[]){ 

  Bike obj = new Bike2();//creating object 

  obj.run();//calling method 

  } 

} 

Output:

Bike is running safely

 


Comments

Popular posts from this blog

Accounting Multiple Choice Questions with answers | Download PDF for MCQs

Difference between Data Mining and Knowledge Discovery (KDD)