Java:从父类(super class)继承的公共(public)方法调用私有(private)方法。

标签 java inheritance polymorphism private

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()中,它调用了StudentgetInfo()。但事实证明并非如此。 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 中没有任何内容使用它。调用来自 PersongetInfo,因为它可用于 PersonprintPerson 方法,因此 Person 已打印。

要重写方法,它不能是私有(private)。您可以将 getInfo 包设为私有(private)(无访问修饰符)、protectedpublic。然后Student将能够覆盖它。

关于Java:从父类(super class)继承的公共(public)方法调用私有(private)方法。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27851516/

相关文章:

java - 对两个对应的数组进行排序时出错

java - 方法句柄查找工具

flutter - 如何为子类属性提供与 Dart 中的父类(super class)不同的类型?

java - Jackson 可以使用它没有编写的 boolean JSON 属性反序列化为具体子类吗?

java - Java 中的枚举和多态性,扑克牌示例

java - Collections.sort 使用什么设计模式?

Java ThreadPoolExecutor释放线程到线程池

java - 我如何做到这一点,以便我的代码不断询问第 1.、2. 和 3. 部分以及选择 :? 在第三次尝试后,扫描仪刚刚关闭

c++ - 读写类 vector

c# - oop 检查返回类型是父类还是子类