| Author |
Dynamic dispatch
|
suavedeep kaur
Ranch Hand
Joined: Jun 02, 2008
Posts: 36
|
|
As it is said that if a superclass contains a method that is overridden by a subclass,then when different types of objects are reffered to through a superclass reference variable ,different versions of the method are executed . class A { void callme(){ System.out.println(" in A's callme method " ); } } class B extends A{ void callme(){ System.out.println(" in b's callme method "); } } class C extends B { void callme(){ System.out.println("in C's callme method "); } } class Dispatch{ public static void main(String args[]){ A a = new A(); a.callme(); B b =new B(); b.callme(); C c=new C(); c.callme(); A ob =new B(); ob.callme(); ob= c; ob.callme(); } } outputs in A's callme method in b's callme method in C's callme method in b's callme method in C's callme method what i am not getting is if the above statement is as true then i can access b's callme method with class B's reference variable only why??? please clarify me this ,though i understand the above statement but how come the b's callme method and c's callme method got executed without there superclass reference . please help me
|
Suavedeep kaur
SCJP
|
 |
Sagar Rohankar
Ranch Hand
Joined: Feb 19, 2008
Posts: 2896
|
|
though i understand the above statement but how come the b's callme method and c's callme method got executed without there super class reference . please help me
Thats not necessary, when you create B`s or C`s object , and assigned them to there respective class reference , there is no problem . The reference varible 'b' and 'c' , are referring to "B" and "C"`s object , and they have 'callme()' method, that`s why they are executing it. There is no polymorphic calls here, they are straightforward method execution !
|
[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
|
 |
Amit Ghorpade
Bartender
Joined: Jun 06, 2007
Posts: 2549
|
|
Hi suavedeep kaur , please UseCodeTags. Your code is unreadable, so you wont get good replies. Hope this helps
|
SCJP, SCWCD.
|Asking Good Questions|
|
 |
 |
|
|
subject: Dynamic dispatch
|
|
|