3

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.

Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21
  • 4
    Because it's entirely possible to define `class Child2 extends Parent implements InterfaceInChild`, and if compiler produced an error here, many things programs do would be impossible. You still get your exception, but at runtime rather than compile time. Compiler doesn't complain because it assumes that **you** have better idea what's going on that it does, since you have ordered the casting operation to be done here. – M. Prokhorov Feb 09 '18 at 11:54
  • I suggest you print out the value of `iface`. Also try casting to something else that isn't declared in your code, like `List` or `JFrame`. – Code-Apprentice Feb 09 '18 at 15:09
  • @M.Prokhorov This assumption of compiler thinking that I know what I'm doing was struggling me - now when that question is marked as duplicate and I see discussions under these questions, it make more sense to me. Thank you providing this helpful comment. – Przemysław Moskal Feb 09 '18 at 15:48
  • @Code-Apprentice I'll try it a bit later as now I don't have a possibility to check it - I'll see what happens. Thank you for giving me this advice. – Przemysław Moskal Feb 09 '18 at 15:49

0 Answers0