Java Casting Interface to Class

后端 未结 8 1260
闹比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:42

    Serializable is NOT an A, so it throws ClassCastException.

    0 讨论(0)
  • 2020-12-05 08:43

    As you point out, this will compile:

    interface MyInterface {}
    
    class A {}
    
    public class InterfaceCasting {
        public static void main(String[] args) {
            MyInterface myObject = new MyInterface() {};
            A a = (A) myObject;
        }
    }
    

    This however, will not compile:

    interface MyInterface {}
    
    class A {}
    
    public class InterfaceCasting {
        public static void main(String[] args) {
            A a = (A) new MyInterface() {}; // javac says: "inconvertible types!"
        }
    }
    

    So, what's going on here? What's the difference?

    Well, since MyInterface is simply an interface, it could very well be implemented by a class that extends A, in which case the cast from MyInterface to A would be legal.


    This code for instance, will succeed in 50% of all executions, and illustrates that the compiler would need to solve possibly undecidable problems in order to always "detect" illegal casts at compile time.

    interface MyInterface {}
    
    class A {}
    
    class B extends A implements MyInterface {}
    
    public class InterfaceCasting {
        public static void main(String[] args) {
            MyInterface myObject = new MyInterface() {};
            if (java.lang.Math.random() > 0.5)
                myObject = new B();
            A a = (A) myObject;
        }
    }
    
    0 讨论(0)
提交回复
热议问题