public interface Interface1 {
void methodFromInterface1();
}
public interface Interface2 {
void methodFromInterface2();
}
public class Superclass implements Interface1, Interface2 {
@Override
public void methodFromInterface1() {
System.out.println("Called methodFromInterface1");
}
@Override
public void methodFromInterface2() {
System.out.println("Called methodFromInterface2");
}
}
public class Testclass {
@Test
public void test() {
Interface1 interface1 = new Superclass();
if (interface1 instanceof Interface1) {
System.out.println("superclass instance of interface1");
interface1.methodFromInterface1();
}
if (interface1 instanceof Interface2) {
System.out.println("superclass instance of interface2");
((Interface2)interface1).methodFromInterface2();
}
}
}
This prints out:
superclass instance of interface1
Called methodFromInterface1
superclass instance of interface2
Called methodFromInterface2
superclass instance of interface1
Called methodFromInterface1
superclass instance of interface2
Called methodFromInterface2
In the Testclass. Superclass is casted to interface1, so the interface1 variable is an Interface1 type. How is it possible that Java allows me to cast the interface1 to a Interface2 object and then call the methodFromInterface2? It should have no information about Interface2 when going from Interface1.
Interface1andInterface2. Now the compiler may generate instructions to search forInterface2at runtime.Superclassclass implements both interfaces. Instances of that class are instances of both interfaces. Casting does not change the type of the object. It makes the compiler see a variable as a different type. Casting is essentially a way to say, "I know better than the compiler".