Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting between interfaces

My question is related to Java language. This is what I got:

interface I1{}
interface I2{}
class C1 implements I1{}
class C3 extends C1 implements I2{}

When

     C1 01;
     C3 o3;
     I1 i1;

etc

And now it turns out that I2 i2 = (I2) i1; is right because at run time i1 actually refers to an object that implements I2. But I don't get it. Interfaces have no relationships between one another, so how can you cast it to an adjacent interface? There is no more code, it is simply a drill in order to prepare for Java certification. Best regards

like image 476
uml Avatar asked Feb 18 '23 14:02

uml


2 Answers

If you cast an Integer to a String, the compiler can stop that as illegal, but, since a class can implement a variety of interfaces, the compiler can't know if you are trangressing when you cast one interface type to another. Consider this code:

I1 i1 = getI1();
if (i1 instanceof I2) {
  I2 i2 = (I2) i1;
}

If the Java compiler didn't allow casts from one interface to another, this perfectly legitimate piece of code wouldn't compile.

like image 80
Marko Topolnik Avatar answered Feb 21 '23 04:02

Marko Topolnik


I2 i2 = (I2) i1; means: I know that the concrete runtime type of the object referenced by i1 implements the I2 interface, so I would like to reference it as an I2. If the concrete runtime type of i1 indeed implements I2, the cast will succeed.

The fact that I1 and I2 have nothing in common doesn't matter. What matters is the actual concrete runtime type of the object referenced by i1.

like image 42
JB Nizet Avatar answered Feb 21 '23 06:02

JB Nizet