| Author |
overriding ignores cast ?? Please explain
|
Asanka Kodippili
Greenhorn
Joined: Dec 09, 2008
Posts: 21
|
|
I get the output "DDDD" for the following code. I thought it would give the output "DCBA" because of the explicit casts done inside m2(). Please explain why these casts are ignored ? class A{ void m1(){ System.out.print("A"); } } class B extends A{ void m1(){ System.out.print("B"); } } class C extends B{ void m1(){ System.out.print("C"); } } class D extends C{ void m1(){ System.out.print("D"); } void m2(){ m1(); ((C)this).m1(); ((B)this).m1(); ((A)this).m1(); } public static void main(String ar[]){ new D().m2(); } }
|
SCJP6 (81%)
Favorite quote from K&B with regard to exam prep : "What matters most is not WHAT you know, its WHEN you know it "
|
 |
Djonatah Stiegler
Ranch Hand
Joined: Oct 30, 2008
Posts: 32
|
|
Please quote your sources. Thanks.
|
From Brazil
|
 |
Asanka Kodippili
Greenhorn
Joined: Dec 09, 2008
Posts: 21
|
|
|
oh..that's hard. I got this from a book fondly called 'Question500' issued by an institute for java studies in sri lanka. (IJTS) hope that's specific enough
|
 |
Djonatah Stiegler
Ranch Hand
Joined: Oct 30, 2008
Posts: 32
|
|
Oww, sorry for that. But it is the rule.. About the question: Overriding is always resolved at runtime, and since you have a reference to the object "D" (and it doesn't matter what is the type you are referring to), you will get the overriding method. Did you understand? (I think was not so clear...) Thanks <><
|
 |
Harvinder Thakur
Ranch Hand
Joined: Jun 10, 2008
Posts: 231
|
|
Here the explicit casts are useless as they are only used by the compiler to resolve whether class C, B and A have a method m1() defined in it. At runtime it is only the actual object type which is used to invoke the method which in this case is object of class D referred by this
|
thanks
Harvinder
|
 |
Asanka Kodippili
Greenhorn
Joined: Dec 09, 2008
Posts: 21
|
|
|
oh ok.. its clear now. Thank you both, Djonatah and Harvinder :-)
|
 |
 |
|
|
subject: overriding ignores cast ?? Please explain
|
|
|