When reading about Android Fragment Callback interfaces, I’ve noticed that there is a possibility to cast Parent
class object to Interface
defined in its subclass body without error or even warning from the compiler. Isn’t in that case compile-time information if Parent
class implements that Interface
to prevent that kind of casting? Here is the code to show what I mean:
class Parent {}
public class Child extends Parent {
private InterfaceInChild iface;
public interface InterfaceInChild {
void foo();
}
public void checkCasting(Parent parent) {
iface = (InterfaceInChild) parent; // no warning, no error
}
public static void main(String[] args) {
Child c = new Child();
c.checkCasting(new Parent()); // throws exception
}
}
This is the exception that is thrown when running that code:
Exception in thread "main" java.lang.ClassCastException: Parent cannot be cast to Child$InterfaceInChild
at Child.checkCasting(Child.java:13)
at Child.main(Child.java:18)
PS. Of course, it’s not the code used in Android Callback Interfaces, I changed names of classes or methods and deleted what’s not necessary to make it clear what is important.