






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







OOC 4 th Sem, ‘B’ Div 2016 - 17 Prof. Mouna M. Naravani
➢ 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.
class Override { public static void main(String args[]) { B subOb = new B( 1 , 2 , 3 ); subOb.show(); // this calls show() in B } } ➢ When show( ) is invoked on an object of type B , the version of show( ) defined within B is used. ➢ That is, the version of show( ) inside B overrides the version declared in A. Output: k : 3
➢ If you wish to access the superclass version of an overridden method, you can do so by using super. class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { super.show(); // this calls A's show() System.out.println("k: " + k); } } Output: i and j : 1 2 k : 3
class Override { public static void main(String args[]) { B subOb = new B( 1 , 2 , 3 ); subOb.show("This is k: "); // this calls show() in B subOb.show(); // this calls show() in A } }
Dynamic Method Dispatch ➢ Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. ➢ Dynamic method dispatch is important because this is how Java implements run-time polymorphism. ➢ We know that, superclass reference variable can refer to a subclass object. ➢ Java uses this fact to resolve calls to overridden methods at run time. ➢ That is, an overridden method is called through the reference variable of a super class. ➢ Ex: DMD.java , FindAreas.java ➢ It is the type of the object being referred to, that determines which version of an overridden method will be executed.
References ➢ Herbert Schildt, “The Complete Reference, JAVA”, 7 th ed