Reputation: 1189
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
Upvotes: 5
Views: 4786
Reputation: 305
To put it simply, an interface is a type, like a bird - not an eagle or a duck. Take concrete implementations of these classes (this is rather silly, but bear with me)
interface Bird {fly();}
interface Swimmer {swim();}
class Eagle implements Bird {fly(){...};}
class Duck extends Eagle implements Swimmer {swim(){...};}
Swimmer i2 = (Swimmer) i1;
This means that your code believes that i1 is an entity that can swim. If i1 is a Duck, this code will work, if it's an eagle, this will fail. The type casting is done at runtime not compile time.
Upvotes: 1
Reputation: 200168
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.
Upvotes: 4
Reputation: 7863
You answered the question yourself ;-)
"[... ]is right because at run time i1 actually refers to an object that implements I2"
Typecasts are evaluated at runtime and not at compiletime. So if the object that i1
points to at runtime is of type I2
there are no errors.
Upvotes: 1
Reputation: 691745
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
.
Upvotes: 3