This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why compiler allow this cast ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why compiler allow this cast ?" Watch "Why compiler allow this cast ?" New topic
Author

Why compiler allow this cast ?

Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 249


interface X{}
class Way
{
public static void main(String args[])
{ X x=null;
Way w=(Way)x;
}
}


Way is not an X.so why compiler allows.Is it because explicit casts says to compiler don`t worry I know what i am doing .
Even it is the case why it doen`t result in runtime exception


Oracle Java Programmer , Oracle SQL Expert , Oracle Java Web Component Developer
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18757
    
  40

Mahtab Alam wrote:


Way is not an X.so why compiler allows.Is it because explicit casts says to compiler don`t worry I know what i am doing .
Even it is the case why it doen`t result in runtime exception



The reason that the compilers allows it, is because, in theory, it is possible to subclass from the Way class *and* implement the X interface. This means that is is possible to have an instance that is both IS-A Way and IS-A X. And since, at compile time, the compiler can't tell if that is the case (or more correctly, nothing in the specification that allows the compiler to confirm the case), the cast is allowed.

Henry

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why compiler allow this cast ?