1

I have an awkward problem with this (propably) simple casting example. Could you please help me?

public class Example1 {

interface ParentIf{}
interface ChildIf extends ParentIf {}
interface OtherIf {}

class ParentCl {}
class ChildCl extends ParentCl {}
class OtherCl {}

    public static void main(String[] args) {
        ChildIf cI = null;
        ParentIf pI = null;
        OtherIf oI = null;
        ChildCl cC = null;
        ParentCl pC = null;
        OtherCl oC = null;

        cI = (ChildIf)oI; //case1 - fine

        cC = (ChildCl)oC; //case2 - inconvertible types

        cI = (ChildIf)oC; //case3 - fine
    }
}

But more awkward is that I don't know why the other two statements are fine.

I can't see any connection between OtherIf and ChildIf. So how is possible to cast the OtherIf to the ChildIf when there is no "extend" between these two interfaces in case1?

vviston
  • 183
  • 1
  • 12

1 Answers1

2
cI = (ChildIf)oI;

is fine because oI could be an instance of a class that implements both ChildIf and OtherIf.

cI = (ChildIf)oC;

is fine because oC could be an instance of a class that extends OtherClass anec implements ChildIf.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I am still just a little bit confused. "Could" means that at this moment oI is not an instance of a class that implements both ChildIf and OtherIf but IntelliJ "knows" that it could be? Sorry I can't see it :/ – vviston Nov 14 '17 at 17:15
  • 1
    oI is a variable which refers to an object of type `OtherIf`. The compiler doesn't care about the concrete type of the object at runtime. It cares about the declared type of the variable: OtherIf. Is it possible for a type to implement both ChildIf and OtherIf? Yes, it's possible. So the cast might succeed, so it makes sense. – JB Nizet Nov 14 '17 at 17:19