This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread 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 Java 8 in Action this week in the Java 8 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: 177

[Added code tags - see UseCodeTags for details]


Mahtab Alam (OCJP )
Blogs : alamsql.blogspot.in , alammahtab.blogspot.in
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: 4242
    
    7

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: 177

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
 
Similar Threads
Explain this generics code?
doubt on wrappers
generics - compiler failure that I do not understand
Generic class question
overloaded var - args