class Dad {
private static final String me = "dad";
protected String getMe() {
return me;
}
protected void printMe() {
System.out.println(getMe());
}
}
class Son extends Dad {
private static final String me = "son";
protected void printMe() {
System.out.println(getMe());
}
}
class Test {
public static void main(String[] args) {
Son son = new Son();
son.printMe();
}
}
In this case, the reference "son" of the "Son" type and since the method printMe() is non-static, the code of the method from the class Son will be executed. But since the Son class has not redefined the method getMe(), the method code from the ancestor class will be executed. So we get "dad".
Second case:
class Dad {
private static final String me = "dad";
protected String getMe() {
return me;
}
protected void printMe() {
System.out.println(getMe());
}
}
class Son extends Dad {
private static final String me = "son";
protected String getMe() {
return me;
}
class Test {
public static void main(String[] args) {
Son son = new Son();
son.printMe();
}
}
Reasoning in a similar way in that case the Son class has not redefined the method printMe(), so the code of the method printMe() from the class Dad should be executed. But we get "Son".Why?
And then what about inheritance? That is, if the heir does not override the ancestor's method, then they together share the code of the ancestor's method?
In the first case son.printMe()
calls Son
's printMe()
(since Son
overrides that method), which calls Dad
's getMe()
(since Son
didn't override that method), which returns "dad".
In the second case son.printMe()
calls Dad
's printMe()
(since Son
didn't override that method), which calls Son
's getMe()
, since Son
overrides that method. Therefore "son" is printed.