• 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: 22124
88
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