为什么我可以在 sub-class 的实例上调用一个私有方法,而它不应该对实例可见?
Why can I invoke a private method on an instance of the sub-class when it shouldn't be visible to the instance?
这个问题类似于Why can a "private" method be accessed from a different instance?
我对那里的答案深信不疑。代码应该 运行。但是,当我将代码更改为这样时
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();
}
}
当我尝试使用多态性来调用 Sub-class Horse 上的私有方法 eat() 时,它起作用并调用了父 class.
的方法
- 不会java动态调用class的实例特定方法吗?
- 这不应该抛出一个运行时间异常吗?
- 这是否意味着该方法实际上是继承的但通常无法访问?
在你的例子中,一个Horse
是一个Animal
。所以是的,Horse
有一个方法叫做 eat
,因为每个 Animal
都有一个这样的方法,每个 Horse
是一个 Animal
.
方法 eat
由 class Animal
定义,并且是 class 中的私有方法。这意味着它只能从 Animal
class 中定义的其他方法中访问,除此之外别无他法。没有 super-/sub-classes,没有包装器,没有容器,什么都没有。甚至 Horse
也没有,即使 它 是一个 Animal
,它也不是 Animal
本身.
所以您的示例按照预期的方式工作。
作为最后的说明,专门回答 "title"、
中的问题
Why can I invoke a private method on an instance of the sub-class when it shouldn't be visible to the instance?
唯一重要的是您从哪里调用该私有方法。您正在从定义它的 class 中调用它。因此它是可访问的。
这个问题类似于Why can a "private" method be accessed from a different instance?
我对那里的答案深信不疑。代码应该 运行。但是,当我将代码更改为这样时
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();
}
}
当我尝试使用多态性来调用 Sub-class Horse 上的私有方法 eat() 时,它起作用并调用了父 class.
的方法- 不会java动态调用class的实例特定方法吗?
- 这不应该抛出一个运行时间异常吗?
- 这是否意味着该方法实际上是继承的但通常无法访问?
在你的例子中,一个Horse
是一个Animal
。所以是的,Horse
有一个方法叫做 eat
,因为每个 Animal
都有一个这样的方法,每个 Horse
是一个 Animal
.
方法 eat
由 class Animal
定义,并且是 class 中的私有方法。这意味着它只能从 Animal
class 中定义的其他方法中访问,除此之外别无他法。没有 super-/sub-classes,没有包装器,没有容器,什么都没有。甚至 Horse
也没有,即使 它 是一个 Animal
,它也不是 Animal
本身.
所以您的示例按照预期的方式工作。
作为最后的说明,专门回答 "title"、
中的问题Why can I invoke a private method on an instance of the sub-class when it shouldn't be visible to the instance?
唯一重要的是您从哪里调用该私有方法。您正在从定义它的 class 中调用它。因此它是可访问的。