-1

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.

Fuzz X
  • 47
  • 1
  • 2
  • 4

5 Answers5

1
  1. 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).

  2. 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.

  3. 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.

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

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.

dunni
  • 43,386
  • 10
  • 104
  • 99
0

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

Community
  • 1
  • 1
pL4Gu33
  • 2,045
  • 16
  • 38
0
  1. 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.

  2. C implements J and you're always allowed to upcast an object.

  3. 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.

Christoffer Karlsson
  • 4,539
  • 3
  • 23
  • 36
0

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.

redge
  • 1,182
  • 7
  • 6