0

I have a Person class and an empty class called MyClass and an empty interface called MyInterface. There is no relationship between the Person, MyClass and MyInterface.

When I cast a Person instance to MyInterface, the compilation passes, but when I cast a Person instance to MyClass, the compilation fails. Why is that?

Below is my code:

class Person {
    public String name;
}

class MyClass {}

interface MyInterface {}

class Test {
    public static void main(String[] args) {
        // Compile passed
        MyInterface myInterface = (MyInterface) new Person();

        // Compile error
        MyClass myClass = (MyClass) new Person();
    }
}
Xi Minghui
  • 95
  • 1
  • 9
  • 1
    Casting to arbitrary interfaces is allowed because the compiler only sees `new Person()` as an expression with type `Person` - it doesn't know if it is `Person` directly, or a subtype of `Person` which also implements `MyInterface`. By contrast, because `MyClass` is a class, it knows that it isn't a subclass or superclass of `Person`, so knows the cast would fail at runtime. – Andy Turner Feb 15 '22 at 16:07
  • Yes, because a *subclass* of `Person` could implement `MyInterface`. – MC Emperor Feb 15 '22 at 16:09
  • I know now, thanks @Andy Turner. – Xi Minghui Jun 16 '22 at 14:59

0 Answers0