class Base {
private void SayHello(){ //PRIVATE
System.out.println("Hello from Base");
}
}
class Derived extends Base {
public void sayHello(){ //PUBLIC
System.out.println("Hello from Derived");
}
}
public class TestHello{
public static void main(String[] args) {
Derived d = new Derived();
Base b = d;
d.sayHello(); //works as expected
b.sayHello(); //Why does this not work?
}
}
我想了解:基类的私有(private)sayHello对派生类是否可见?或者说是重新定义?为什么从基指针调用派生的 sayHello 不起作用?我的意思是,如果它是公共(public)的(在 Base 中),那么就会调用派生类中的 sayHello。所以,我不明白的是,如果它必须从派生类调用公共(public) sayHello,那么为什么要查看基类的访问修饰符?
另外,如果您能给我指出一些简洁的资源来帮助我更深入地理解这一点,我将非常感激。谢谢!
最佳答案
is the private sayHello from base class visible to the derived class?
当然不行,因为它有 private
访问修饰符。
有关访问修饰符的更多信息:
Controlling Access to Members of a Class
or is it a redefinition?
正如您在该问题的已接受答案中看到的:
What's the difference between redefining a method and overriding a method?
术语“重新定义”并不常用。我们可以谈论“重写”和“重载”,但在您的例子中,来自 Derived
类的 sayHello
是一种新方法,它不是 的重载版本来自
。Base
类的 >sayHello
And why does the call to the derived sayHello from the base pointer does not work?
仅仅因为您尝试调用不属于开放类接口(interface)的方法。
I mean, if it were public (in Base), then the sayHello from the derived class would have been called.
当然,这是预期的多态行为。在本例中,Derived
类中的 sayHello
会覆盖 Base
类中的 sayHello
,因此您可以调用 >sayHello
来自 Derived
类,通过对 Base
类的引用。
So, what I can not understand is that if it has to call the public sayHello from the derived class, then why look at the access modifier from the base class?
因为您使用了对 Base
类的引用,并且 Base
类的接口(interface)中没有 sayHello
方法。
我在这里找到了一个很好的讨论:
Overriding private methods in Java
可能对您也有用:
希望对您有帮助。
关于java - Java 基类中的私有(private)方法的动态绑定(bind)如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33983307/