Method Overriding in Java


What is Method Overriding- Method Overriding in Java is where the name of the method is same in Parent class and Child class but thr behavior of the method depends on the reference given to the object at the run time. In other words , sublclass method can implement the method and it's behavior according to it's requirement.

Let's have a look on below program.

Example

package methodOverriding;
//Class Vehicle
public class Vehicle {
void wheels()
{
System.out.println("Vehicles are of 2 or 4 wheels");
}
}
Class Car
public class Car extends Vehicle {
void wheels()
{
System.out.println("Cars are of 4 wheels");
}
}
//Class Main
public class OverRideDemo {
public static void main(String[] args) {
Vehicle v=new Vehicle(); //Vehicle reference and it's object
Vehicle c=new Car(); //Vehicle reference but Car object
v.wheels(); //method in Vehicle Class
c.wheels(); //method in Car class
}
}


Output

Vehicles are of 2 or 4 wheels
Cars are of 4 wheels


Explanation

  • In above program, we created two classes Vehicle and and it's subclass Car having same method name and behavior.
  • In the Main class we created object of Vehicle and it's reference and second object of Vehiclebut Car reference.
  • So first the method in Vehicle class is executed then method in Car class is executed. Because the object may be of Vehicle class but the reference is of Carclass.


  • Using super Keyword.

    To access the method in Super class in subclass ,the super keyword is used.

    Example

    package methodOverriding;
    //Class Vehicle
    public class Vehicle {
    void wheels()
    {
    System.out.println("Vehicles are of 2 or 4 wheels");
    }
    }
    Class Car
    public class Car extends Vehicle {
    void wheels()
    {
    super.wheels();
    System.out.println("Cars are of 4 wheels");
    }
    }
    //Class Main
    public class OverRideDemo {
    public static void main(String[] args) {
    Vehicle c=new Car(); //Vehicle reference but Car object
    c.wheels(); //method in Car class
    }
    }


    Output

    Vehicles are of 2 or 4 wheels
    Cars are of 4 wheels


    Method Overriding Rules
  • The syntax and return type and name of the overriden method should be same as in parent class.
  • final method cannot be overridden.
  • Static method cannot be overridden.
  • To override a method , it should be inherited first.
  • Method Overriding in Java Method Overriding in Java Reviewed by LanguageExpert on October 01, 2018 Rating: 5

    No comments