aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Accessing an object using a reference variable of an unrelated Interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Accessing an object using a reference variable of an unrelated Interface" Watch "Accessing an object using a reference variable of an unrelated Interface" New topic
Author

Accessing an object using a reference variable of an unrelated Interface

Andy James
Ranch Hand

Joined: Aug 22, 2005
Posts: 90
Why is casting an object of type Person to an unrelated Interface Printable allowed, as follows:



cheers
Andy
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18848
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing an object using a reference variable of an unrelated Interface