覆盖私有方法和可见性 [英] Overriding private methods and visibility
问题描述
我知道私有方法隐藏在Derived类中,并且不能重写,但是我的问题不同..请经历以下问题.在下面所述的问题中提到了我的问题:
I know that private methods are hidden in Derived class and they cant be overridden but my question is different.. Please go through the following problem. My question is mentioned in the problem stated below:
TestPolymorphism.java
TestPolymorphism.java
class CheckParent {
private void display() {
System.out.println("This is parent class");
}
}
class CheckChild extends CheckParent {
void display() {
System.out.println("This is child class");
}
}
public class TestPolymorphism {
public static void main(String[] args) {
CheckParent cp = new CheckChild();
cp.display(); // This will throw error as display() method id private
// and invisible to child class
}
但是,在下面的代码段中没有引发异常.
However, in following code snippet no exception is thrown.
CheckParent.java
CheckParent.java
public class CheckParent {
private void display() {
System.out.println("This is parent class");
}
public static void main(String[] args) {
CheckParent cp = new CheckChild();
cp.display(); /*This will print "This is parent class" without any error
* my question is why no error is thrown like above case
* as here too display() method is private and invisible to
* derived class */
}
}
class CheckChild extends CheckParent {
void display() {
System.out.println("This is child class");
}
}
}
推荐答案
对于构造函数,使用私有,最终或静态方法静态(早期)绑定.对于所有其他对象,使用动态(后期)绑定.检查一下:
For constructor, private, final or static methods static(early) binding is used. For all others dynamic(late) binding is used. Check this out:
http://geekexplains. blogspot.co.uk/2008/06/dynamic-binding-vs-static-binding-in.html
这篇关于覆盖私有方法和可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!