Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why compiler thinks that it can be casted

 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Added code tags - see UseCodeTags for details]
 
Bhavesh Saraswat
Greenhorn
Posts: 18
Java Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 391
1
Java MySQL Database PHP
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thhanks for explaining understood
 
Ashish Anant Patil
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey iam new here...so jst wanted 2ask t question above..is it frm latest scjp xam?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic