Java Casting Interface to Class

后端 未结 8 1361
闹比i
闹比i 2020-12-05 08:03
public class InterfaceCasting {

    private static class A{}

    public static void main(String[] args) {
        A a = new A();
        Serializable serializable          


        
8条回答
  •  臣服心动
    2020-12-05 08:19

    Java language specification states, that:

    Some casts can be proven incorrect at compile time; such casts result in a compile-time error.

    And later on the show The detailed rules for compile-time legality of a casting conversion of a value of compile-time reference type S to a compile-time reference type T - beware, they are very complex and hard to understand.

    The interesting rule is:

    • If S is an interface type:
      • If T is a type that is not final (§8.1.1), 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 T does not implement S, a subclass of T might).

    In your example, it's perfectly clear, that the cast is illegal. But consider this slight change:

    public class InterfaceCasting {
    
        private static class A{}
        private static class B extends A implements Serializable{}
    
        public static void main(String[] args) {
            A a = new A();
            Serializable serializable = new B(){};
            a = (A)serializable;
        }    
    }
    

    Now a cast from a Serializable to A is possible at runtime and this shows, that in those cases, it's better left to the runtime to decide if we can cast or not.

提交回复
热议问题