File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on Reference assignment for Interface references.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on Reference assignment for Interface references.." Watch "Question on Reference assignment for Interface references.." New topic
Author

Question on Reference assignment for Interface references..

Tanya Shetty
Ranch Hand

Joined: Jun 17, 2009
Posts: 40


source : Ethuware

Question : Interface I1 does not extend Interface I2, and also the vice versa is not true.. so when I give the compiler the following line of code,

I1 i1 = null; I2 i2 = (I2) i1; // it compiles fine.

Why does the compiler allow this assignment I2 i2 = (I2)i1; when there is clearly no inheritance between them ??



kevinn lee
Ranch Hand

Joined: Feb 15, 2010
Posts: 87
compiler compiles any code unless it knows exactly that the particular casting is impossible.
In your case there can be a class which implements both the interfaces.Then both i1 and i2 can refer to an object of that class and the casting between I1 and I2 makes sense.
Prasad Kharkar
Ranch Hand

Joined: Mar 07, 2010
Posts: 438

C1 IS-A I1
C2 IS-A I2
C3 IS-A C1 and IS-A I2 from the given data
If C1 can refer to object of c3 that passes IS-A for both C1 and I2
then C1 should also be able to refer to reference of I2 isn't it?

SCJP 6 [86%] June 30th, 2010
OCPWCD [84%] March 26th, 2013
If you find any post useful, click the "plus one" sign on the right
Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
I tried compiling the code



and I receive the following errors:

C3.java:6: class, interface, or enum expected
C1 o1;
^
C3.java:7: class, interface, or enum expected
C2 o2;
^
C3.java:8: class, interface, or enum expected
C3 o3;
^
3 errors



Is this is typing error, or something else?


Marriage Made in Heaven
http://www.youtube.com/user/RohitWaliaWedsSonia
Tanya Shetty
Ranch Hand

Joined: Jun 17, 2009
Posts: 40
Thanks! Got it!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Question on Reference assignment for Interface references..
 
Similar Threads
inheritance
Help :: Illegal Casting Question
help me for this question... (interface question)
Interfaces?
References and casting