Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Casting Interface to Class

Tags:

java

casting

public class InterfaceCasting {

    private static class A{}

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

}

Compilation succeed but Runtime exception

Exception in thread "main" java.lang.ClassCastException: InterfaceCasting$1 cannot be cast to InterfaceCasting$A

WHY COMPILATION SUCCEED? Compiler must known that serialiazable is not A?

like image 766
komenan Avatar asked Aug 27 '10 09:08

komenan


People also ask

Can you cast an interface to a class Java?

Java For TestersYes, you can. If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.

Can I cast interface to class?

If you have a concrete class, you can cast it to the interface. If you have an interface, it is possible to cast to the concrete class. Generally, you only want to go in the first direction. The reason being that you shouldn't know what the concrete class is when you have only a pointer to the interface.

How do you cast an interface in Java?

interface I1 { } interface I2 { } class C1 implements I1 { } class C2 implements I2 { } public class Test{ public static void main(String[] args){ C1 o1 = new C1(); C2 o2 = new C2(); Integer o3 = new Integer(4); I2 x = (I2)o1; //compiler does not complain I2 y = (I2)o3; //compiler complains here !! } }


1 Answers

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;
    }
}
like image 53
aioobe Avatar answered Oct 30 '22 21:10

aioobe