Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Reference assignment for Interface references..

 
Tanya Shetty
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Tanya Shetty
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! Got it!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic