You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When the subclass object is called then the display method inherited
from the super class is shadowed and the subclass display method is
executed.
Super Class method never be called upon the object of SubClass.
In the given example program the super class have a method called
display which is saying hello and another class subclass is taken where it
inherits the display method from super class and redefined the method.
When a super class reference holding the object of subclass and
overridden method is called then method of object will be called it is
Dynamic Method Dispatch.
4. super class reference of subclass object ( Parent obj = new Child() )
In the given example meth2() is redefined in the subclass.
Super Class reference can have Object of Sub Class but a SubClass reference cannot have Super Class Object.
A Super Class Reference can hold the Object of Sub Class, but it can call only those methods which are present in
super class.
Methods are called depending on the object not the reference then the overridden object is called it
is Runtime Polymorphism.
Dynamic Method Dispatch means calling a Method dynamically because program make the decision at runtime for which
object to be called.
7. Real Life Case of Dynamic Method Dispatch
classAnimal {
publicvoidMakeSound() {
System.out.println("Iam an Animal And this is my sound");
}
}
classDogextendsAnimal {
@OverridepublicvoidMakeSound() {
System.out.println("Haw Haw");
}
}
classCatextendsAnimal {
@OverridepublicvoidMakeSound() {
System.out.println("Meow Meow");
}
}
classBirdextendsAnimal {
@OverridepublicvoidMakeSound() {
System.out.println("Sew Sew");
}
}
publicclassSolve {
// public static void FunForDog(Dog dog)// {// dog.MakeSound();// }// public static void FunForCat(Cat cat)// {// cat.MakeSound();// }// public static void FunForBird(Bird bird)// {// bird.MakeSound();// }// Good Practicing To Follow To Achieve Clean CodepublicstaticvoidGeneric(Animalanimal) {
animal.MakeSound();
}
publicstaticvoidmain(String[] args) {
Generic(newBird()); // Anonymous ObjectGeneric(newCat()); // Anonymous ObjectGeneric(newBird()); // Anonymous ObjectGeneric(newAnimal()); // Anonymous Object
}
}
8. Rules For Overriding
Do and Don’t of Method Overriding
Signature must be same in method overriding.
If the method name is different the method is not overridden ,but it is overloaded.
Argument may be different but the parameter must be same.
Return type must be same, if it is not same then the method is neither overridden nor overloaded.
Final and static methods cannot be overridden.
Method can be overridden with same or lenient (public, protected) access modifiers but the stricter(private) access modifiers cannot be used in subclass.