I do not understand how the casting is done on var2 The following line does not Compile as methodA1() not present in interface reference I1
String var = i1.methodA1();
Hence I1 requires a cast to invoke methodA1 I do not understand how the casting is done as A1 is not the child class of I1. Child c = (Child)p; According to the syntax of downcasting A1 should be the Child class and i1 should be the parent object but neither is A1 the child class nor is i1 it's parent object I also do not understand how I am able to call to call toString() from i1 and i2 because toString() is defined in class A1 and toString() is not declared in I1 and I2.
interface I1 {
void methodI1(); //public static by default
}
interface I2 extends I1 {
void methodI2(); //public static by default
}
class A1 {
public String methodA1() {
String strA1 = "I am in methodC1 of class A1";
return strA1;
}
public String toString() {
return "toString() method of class A1";
}
}
class B1 extends A1 implements I2 {
public void methodI1() {
System.out.println("I am in methodI1 of class B1");
}
public void methodI2() {
System.out.println("I am in methodI2 of class B1");
}
}
public class InterFaceEx {
public static void main(String[] args) {
I1 i1 = new B1();
I2 i2 = new B1();
String var2 = ((A1) i1).methodA1();// I1 requires a cast to invoke methodA1. How is this casting happening?
System.out.println("var2 : " + var2);
String var4 = i1.toString();// How I am able to call toString()?
System.out.println("var4 : " + var4);
String var5 = i2.toString();// How I am able to call toString()?
System.out.println("var5 : " + var5);
}
}