Imagine we have class C that implements interfaces I and J declared as ;
I i = new C();
why do these 3 not give errors (especially the last one):
1) C c = (C)i;
2) J j = (J)i;
3) i = (I)null;
thanks in advance.
Imagine we have class C that implements interfaces I and J declared as ;
I i = new C();
why do these 3 not give errors (especially the last one):
1) C c = (C)i;
2) J j = (J)i;
3) i = (I)null;
thanks in advance.
C c = (C)i;
Since i
can hold instance of type C
there is no problem with allowing by compiler casting I
to C
type reference (if casting will succeed at runtime we will be sure that all methods from C
reference will be supported by instance which will also be of type C
or its subtype).
J j = (J)i;
Since there is a possibility (like in our case) that instance stored in i
will also implement J
interface compilers allows us to cast between references of unrelated interfaces. But if instance stored in i
will not implement J
then we will get ClassCastException
at runtime.
i = (I)null;
Well, null
can be assigned to any reference so there is no problem with allowing it to be assigned to i
or cast it.
The first one works, because i is an instance of C (even if the reference is of type I, but for the casting the reference type is irrelevant).
The second works, because i is an instance of C and thus also an instance of J (since C implements J). The reference type is irrelevant for casting.
The interfaces is a different "view" from the object. When you debug it, there is always the "C" object.
For Null you can look here: No Exception while type casting with a null in java
Works because i is a reference variable of I, but that holds an instance of C. You're allowed to downcast an object if the object is an instance of the class you're casting to.
C implements J and you're always allowed to upcast an object.
I guess it's becuase i is a reference variable, which is allowed to have a null value, and you're giving it a value of null.
Once you have created the object and assigned it to i with the statement.
I i = new C();
The object is still a C even though the variable refering to it is defined as I.
SO
C c = (C)i;
just assigns the same object to a new variable that is defined as C. And as the object is of type C there is no problem.
j = (J)i;
just assigns the same object to a new variable that is defined as J. And as the object is of type C which implements the interface J it is also of type J so there is no problem.
i = (I)null;
Just sets the variable i to null.