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?
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.
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.
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 !! } }
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With