Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.493 :

Posted: Tue Apr 03, 2012 6:13 am
by ETS User
Hi,

Really between interface references all is possible and compilable, not?

Is different for example than when we work with assignations between objects, in this case the inheritance tree is considered.

Runnable r2 = (Runnable) new Object();
MyInterface my1 = (MyInterface) r2;

The compiler does not check anything?

Really r2 is not a reference a object that implements MyInterface...

Re: About Question com.enthuware.ets.scjp.v6.2.493 :

Posted: Tue Apr 03, 2012 7:54 am
by admin
Not sure if I understand your question but the given code is valid. The compiler can only check whatever can be logical deduced from the code. In this case, when the compiler see the line "MyInterface my1 = (MyInterface) r2;", it thinks it is possible that r2 points to an object that implements MyInterface because the reference type of r2 is an interface and not a class and so it accepts the statement. Of course, it will fail at run time.

This is because at compile time only the declared information about the variables is available. The actual objects are created at run time and their exact types can be known only at run time because of polymorphism.

HTH,
Paul.

Re: About Question com.enthuware.ets.scjp.v6.2.493 :

Posted: Mon Mar 02, 2015 2:03 pm
by malaybiswal
How below is legal? I1 and I2 are 2 interfaces and there is no relationship between them .
I2 i2 = (I2) i1;

Re: About Question com.enthuware.ets.scjp.v6.2.493 :

Posted: Mon Mar 02, 2015 9:19 pm
by admin
There is no need for a relationship between interfaces because a class can implement multiple interface. For example, i1 could point to an object of a class that implements I1 as well as I2, therefore, the compiler has to allow I2 i2 = (I2) i1;