public class Test {
public static void main(String args[]){
Student s = new Student();
s.printPerson();
}
}
class Person{
private String getInfo(){
return "Person";
}
public void printPerson(){
System.out.println(getInfo());
}
}
class Student extends Person{
private String getInfo(){
return "Student";
}
}
输出是人
。我对这个结果很困惑。在main方法中,引用类型是Student
。所以在执行s.printPerson()
时,应该执行Student
的方法。关键是,在从父类(super class)继承的公共(public)方法中,调用了哪个私有(private)方法?为什么?
我认为在s.printPerson()
中,它调用了Student
的getInfo()
。但事实证明并非如此。 IDE 告诉我
private String getInfo(){
return "Student";
}
从未使用过。
有人可以帮我解决这个问题吗?
最佳答案
在 Java 中,private
methods are not inherited .
A subclass does not inherit the
private
members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
您无法通过创建另一个 getInfo
方法来覆盖 getInfo
,因为它不是继承的。这就是为什么您的 IDE 会向您发出“从未使用”警告,因为 Student
中没有任何内容使用它。调用来自 Person
的 getInfo
,因为它可用于 Person
的 printPerson
方法,因此 Person
已打印。
要重写方法,它不能是私有(private)
。您可以将 getInfo
包设为私有(private)(无访问修饰符)、protected
或 public
。然后Student
将能够覆盖它。
关于Java:从父类(super class)继承的公共(public)方法调用私有(private)方法。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27851516/