- Over Riding is also known as Runtime – polymorphism/Dynamic – Binding/Late-Binding
- In a class hierarchy, when a method in the sub class has the same name and same type signature as that of the method in the superclass, Then the method in the subclass is said to be over ridden by the super class.
- Method overriding occurs only when the Names and their types (Data Types) of two methods are identical.
- This shows the implementation of INHERITANCE.
- It is a mechanism where calls to the overridden method is resolved at runtime (hence Runtime Polymorphism).
Why Over
ridden Methods?
- Runtime polymorphism is supported.
- Concept of polymorphism is established.
- Rules of Over Riding:
- Same name and same type signature.
- Final methods cannot be overridden.
- Private methods doesn’t participate, because these methods are not visible to the child class.
package
org.javanoobs.overriding;
// This is the super Class.
public class Vehicle {
public void move(){
System.out.println(" Vehicle can
move.. ");
}
}
package
org.javanoobs.overriding;
// This class is a subclass.
public class MotorBike extends Vehicle {
public void move(){
System.out.println(" Motorbikes
can move and Accelerate !!! Wroom... ");
}
}
package
org.javanoobs.overriding;
// This is the main method..
public class MainMethod {
public static void main(String args[]){
Vehicle
vh = new MotorBike(); // First object
vh.move();
vh
= new Vehicle(); // Second object
vh.move();
}
}
OUT PUT:
Motorbikes can move and Accelerate !!!
Wroom...
Vehicle can move..
No comments:
Post a Comment