Method Overriding in java. || What is method overriding in java. || explain method overriding in java. || Example of overriding in java



Method Overriding

In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden. Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. If you wish to access the superclass version of an overridden function, you can do so by using super.

Example:

class Vehicle

{ int Wheels;

String Name;

void show()//super class method

{ System.out.println("Vehicle :");

System.out.println("Wheels : " + Wheels);

System.out.println("Name : " + Name);

}

}

class Car extends Vehicle

{ String Brand;

void show() //overrides the superclass show()

{ System.out.println("Car :");

System.out.println("Wheels : " + Wheels);

System.out.println("Brand : " + Brand);

}

}

class MotorCycle extends Vehicle

{ String Brand;

void show(int wheels)//overloads the superclass show()

{ System.out.println("Motor Cycle has " + wheels + " wheels."); }

}

class VehicleTest

{

public static void main(String args[])

{

Car myCar = new Car();

myCar.Wheels = 4;

myCar.Brand = "Honda";

myCar.show();

MotorCycle myMoto = new MotorCycle();

myMoto.show(2);

}

}

Post a Comment

Please do not enter any spam link in the comment box