Why does it compile when casting to an unrelated interface?

孤者浪人 提交于 2019-11-26 19:05:49

The compiler does not know that this won't work: You could have a subclass of BlackInk that implements Printable. Then the cast would be fine.

In situations where the compiler knows it won't work, you will get an error.

For example, if you make BlackInk final (so that there can be no subclasses) you get an error.

According to java language specification section: 5.5.1 Reference Type Casting:

For a compile-time reference type S(source) and a compile-type reference type T(target); While casting conversion from S to T, If S is a class Type

  • If T is a Class type:

    1. Then either T is a subtype of S or S is a subtype of T. Otherwise, a compile time error occurs.
    2. if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types, and that the erasures of X and Y are the same, a compile-time error occurs.

      class S{}
      
       class T extends S{}
        ////
      
        S s = new S();
        T t = (T)s; // run time ClassCastException will happen but no compile time error
      
  • If T is an Interface type:

    1. If S is not a final class, then, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types, and that the erasures of X and Y are the same, a compile-time error occurs. Otherwise, the cast is always legal at compile time (because even if S does not implement T, a subclass of S might)
    2. If S is a final class, then S must implement T, or a compile-time error occurs.

That is for your case, even if class casting is detected in compile time, Interface casting is detected in runtime.

Type casting happens at run time(remember run time polymorphism). At compile time compiler doesn't see anything wrong with the code and compiles and at run time it tries to type cast blackink to printable and is unable to do so as blackink doesn't implement printable , hence the error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!