This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
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

Accessing an object using a reference variable of an unrelated Interface

 
Andy James
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is casting an object of type Person to an unrelated Interface Printable allowed, as follows:



cheers
Andy
 
Henry Wong
author
Marshal
Pie
Posts: 21362
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andy James wrote:Why is casting an object of type Person to an unrelated Interface Printable allowed, as follows:



cheers
Andy



What should the compiler do in this case?



Basically, it is not possible, at the time of the cast, to determine whether the Person reference is referring to a Person object that implements Printable (or not) -- hence, it is allowed at compile time (but will fail at runtime). On the other hand, try making the Person class final, and see what happens.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic