简体   繁体   中英

Java: A public method inherited from superclass invokes a private method.

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";
  }
}

The output is Person . I am confused with this result. In the main method, the reference type is Student . So when executing s.printPerson() , it should executes the method of Student . The key point is, in the public method inherited from superclass, which private method is invoked? And why?

I thought in s.printPerson() , it invokes getInfo() of Student . But it turns out not. The IDE tells me

private String getInfo(){
      return "Student";
}

is never used.

Can anyone help me with this please?

In 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.

You cannot override getInfo by creating another getInfo method because it's not inherited. That's why your IDE gave you the "never used" warning, because nothing in Student uses it. The getInfo from Person is called, because it is available to Person 's printPerson method, so Person is printed.

To override a method, it must not be private . You can make getInfo package-private (no access modifier), protected , or public . Then Student will be able to override it.

You use the private modifier. This modifier means that the method is only visible from within the class itself, not other classes, not even its sub- and superclasses. So when you call getInfo() from class Person , the only method visible is the method defined in the Person class. Effectively this means that private methods are not inherited in Java.

Try to change the private modifier to protected . Then the subclasses can see the method from the superclass, and so they can overide the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM