I have this example, I can’t understand why java allows you to cast obj with an interface that does not implement it.
public interface Interface { public void whoIam(); } public class SuperClass { } public class SubClass extends SuperClass implements Interface { public void whoIam() { System.out.println("IM a SubClass"); } public static void main(String[] args) { SuperClass a = new SubClass(); Interface b = new SubClass(); Interface c = (Interface) new SuperClass(); c.whoIam(); }
This line below should not compile, because SuperClass does not implement the interface:
Interface c = (Interface) new SuperClass();
It will throw a "java.lang.ClassCastException:"
So, I think there is a reason the compiler resolves this line.
I would like to know when we can use obj with an interface when it does not implement it.
thanks
Kikou source share