Reputation: 1658
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?
Upvotes: 2
Views: 92
Reputation: 144
Case 2:
son.printMe()
will call Dad
class printMe()
as is not not everriden in Son
class. Now it will look for getMe()
in the nearest implementation class in the herarchy, i.e. Son
class. Now Son#getMe()
will look for the variable me
in this implementation class, and finds with value "son"
, so is getting printed. Keep in mind that private static final String me = "dad";
and private static final String me = "son";
are two different private variables belong to two different classes. Had there been no definition of me
variable in the Son
class, you would have got a compilation error.
Upvotes: 0
Reputation: 1
You are overriding same same method with tge diff class but the parameters are same for that tge main method is calling the son method
Upvotes: 0
Reputation: 312219
In the second scenario, you're calling Dad#printMe
, which, in turn, calls getMe
. Since Son
does override it, Son#getMe
is called. That method returns "Son", which is then printed by printMe
.
Upvotes: 1
Reputation: 394136
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.
Upvotes: 4