Hi I came upon with a snippet of this code on a book. But somehow I could not fully understand how java uses the private method over the public
package com.toro.employee2;
public class Deer {
public Deer() {
System.out.print("Deer");
}
public Deer(int age) {
System.out.print("DeerAge");
}
private boolean hasHorns() {
return false;
}
public static void main(String[] args) {
Deer deer = new Reindeer(5);
System.out.println("," + deer.hasHorns());
}
}
class Reindeer extends Deer {
public Reindeer(int age) {
System.out.print("Reindeer");
}
public boolean hasHorns() {
return true;
}
}
The output is DeerReindeer,false My questions is:
When I change the Deer class hasHorns() method to other access modifier other than PRIVATE it will use the Reindeer class hasHorns() method thus returning true but if the Deer class hasHorns() method uses the PRIVATE access modifier it will return false instead.
It would be great if you could explain how this works.
private
methods are not inherited and not overridden. Thus, when you calldeer.hasHorns()
, the method executed isDeer#hasHorns
. In fact, if you move themain
method fromDeer
toReindeer
or another class, that piece of code will fail.