Java method overriding
If a method is declared in the parent class and method with same name and parameter list is written inside the subclass then it is called method overriding.
Contents
Rules for Method Overriding :
- Method Must have Same Name as that of Method Declared in Parent Class
- Method Must have Same Parameter List as that of Method Declared in Parent Class
- IS-A relation should be maintained in order to Override Method.
Why we need to override method ?
Consider the following Parent Class -
class Human { void talk() { System.out.println("Talking Human"); } }
Conside following child class -
class Male extends Human { public static void main(String args[]) { Male m1 = new Male(); m1.talk(); } }
We want to provide the different implementation to talk() method for Male and Human class. Using override we can provide different implementations for talk() in Parent Class and in Child Class.
Method Overriding Example :
Vehicle.java
package com.c4learn.inheritance; public class Vehicle { public void vehicleMethod() { System.out.println("Method in Vehicle."); } }
TwoWheeler.java
package com.c4learn.inheritance; public class TwoWheeler extends Vehicle { public void vehicleMethod() { System.out.println("Method" + " in TwoWheeler."); } public static void main(String[] args) { TwoWheeler myBike = new TwoWheeler(); Vehicle myVehicle = new Vehicle(); myVehicle.vehicleMethod(); myBike.vehicleMethod(); } }
Output of the Program :
Method in Vehicle. Method in TwoWheeler.