Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance casting

 
Cathy Song
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Test{
public static void main(String args[]){
A a = (A) new Object(); //line 1
B b = (B) new A(); //line 2
}
}

class A{
}

class B extends A{
}

How come line 1 and 2 compile? We are performing a narrowing conversion.

Thanks.
-Cathy
 
jiju ka
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A narrowing conversion is not detected at compile time. It is detected only at runtime. At Runtime you will get a ClassCastException.

In the above code you can see that an instance of Object is wider than an instance of A. Similarly A is wider than B. But the compiler don't know about which type is wider than which or vice versa.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by jiju ka:
A narrowing conversion is not detected at compile time. It is detected only at runtime. At Runtime you will get a ClassCastException.

In the above code you can see that an instance of Object is wider than an instance of A. Similarly A is wider than B. But the compiler don't know about which type is wider than which or vice versa.


I think the OP is asking why the compiler is so stupid! Why doesn't the
compiler know -- it is pretty obvious in these two cases.

The problem is that in other cases it's very hard to determine if a
cast will fail or succeed. And in general, it's undecidable. Because
of that, compiler give up right way and don't try to deduce if a
cast will fail -- they typically don't give you a heads-up warning, for example.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic