wood burning stoves*
The moose likes Beginning Java and the fly likes Inheritance casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inheritance casting" Watch "Inheritance casting" New topic
Author

Inheritance casting

Cathy Song
Ranch Hand

Joined: Jul 01, 2003
Posts: 92
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

Joined: Oct 12, 2004
Posts: 306
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

Joined: Sep 16, 2005
Posts: 1780
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.


There is no emoticon for what I am feeling!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inheritance casting
 
Similar Threads
Casting
Local inner classes
Type Conversion
Benefits of Reference Type
casting