In the following program, if msg() in A is declared as public, b.display() in main() calls B's version of msg(). But, if msg() in A is declared as private, b.display() in main() calls A's version of msg(). Could you please tell me why this behaviour?
Thanks in advance.
class A {
private String msg() {
return "Message from class A";
}
void display() {
System.out.println(msg());
}
}
class B extends A {
public String msg() {
return "Message from class B's msg()";
}
}
class Tests {
public static void main(String args[]) {
B b = new B();
// private version of msg defined in A will be called
// if msg is defined as public in A, the version of msg defined in B is called
b.display();
// the version defined in B is called
System.out.println(b.msg());
}
}