public class Print1 {
int x = 1;
public void print(A a) { System.out.println(x); }
public void print(B b) { System.out.println(x+1); }
}
public class Print2 extends Print1 {
int x = 3;
public void print(A a) { System.out.println(x); }
public void print(B b) { System.out.println(x+1); }
public void print(C c) { System.out.println(x+2); }
}
// a tester class with main method
A a = new A(); B b = new B(); C c = new C();
Print1 p1 = new Print1();
Print2 p2 = new Print2();
p1 = p2;
System.out.println(p1.x); // Call 1, p1 is from Type Print1
p1.print(c); /* Call 2
//p1 is from Type Print2, print(B b) will be called */`
Class B is a subclass of Class A and C is a subclass of B.
why in Call 1
P1
from typePrint1
even though it is referencing to Object of typePrint2
and in call 2 it is behaving as reference toPrint2
-object?why in Call 2
print(B b)
is called fromPrint2
and notprint(C c)
?
This is the most confusing things for me so far in Java. Thank you for your help.