• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overriding ignores cast ?? Please explain

 
Asanka Kodippili
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
}

}
 
Djonatah Stiegler
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please quote your sources.

Thanks.
 
Asanka Kodippili
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
 
Asanka Kodippili
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh ok.. its clear now. Thank you both, Djonatah and Harvinder :-)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic