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 thinks that it can be casted 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 thinks that it can be casted" Watch "Why compiler thinks that it can be casted" New topic
Author

Why compiler thinks that it can be casted

Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 249

[Added code tags - see UseCodeTags for details]


Oracle Java Programmer , Oracle SQL Expert , Oracle Java Web Component Developer
Bhavesh Saraswat
Greenhorn

Joined: Jan 20, 2013
Posts: 18

at the time of compilation compiler thinks X as an Object type because <X extends Object> . So an object of Object class can be casted to any of its subtypes, which is Double, because they come in same hierarchy in the inheritance tree.

So the compiler will always allow the cast.


OCPJP SE6
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4370
    
    8

Casting is effectively telling the compiler "Trust me. I know you think that's an X, which could be anything, but I know it's going to be a Double, so treat it like a double". You're overriding the compiler, so the compiler lets you do it and relies on the runtime to catch any errors.

The compiler will only stop you if it knows that you're wrong - if the cast cannot possibly work. As an example, try changing your first line to X extends Integer.
Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 249

Thhanks for explaining understood
Ashish Anant Patil
Greenhorn

Joined: Mar 17, 2013
Posts: 7
Hey iam new here...so jst wanted 2ask t question above..is it frm latest scjp xam?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why compiler thinks that it can be casted