This question is similar to Why can a "private" method be accessed from a different instance?
I am convinced with the answer there. The code should run. However when I change the code to be like this
class Horse extends Animals{
}
public class Animals {
private void eat(){
System.out.println("Generic Eating");
}
public static void main(String[] args){
Animals h = new Horse();
h.eat();
}
}
when I try to use polymorphism to invoke the private method eat() on the Sub-class Horse it works and calls the method of the parent class.
In your example, a Horse
is an Animal
. So yes, a Horse
has one method called eat
, because every Animal
has one such method, and every Horse
is an Animal
.
The method eat
was defined by the class Animal
, and is a private method in that class. Which means it can only be accessed from within other methods defined in the Animal
class, and nothing else. No super-/sub-classes, no wrappers, no containers, no nothing. Not even a Horse
which, even though it is an Animal
, it is not Animal
itself.
So your example works in the way it was expected to work.
As a final note, answering specifically to the question in the "title",
Why can I invoke a private method on an instance of the sub-class when it shouldn't be visible to the instance?
The only thing that matters is from where you are invoking that private method. You are invoking it from within the class in which it was defined. Therefore it is accessible.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.