0

This is a practice question from my textbook. It prints:

Person

Person

I'm wondering why it won't print Person and then Student. Shouldn't getInfo be overrided for the Student instance, and print Student? I must be misunderstanding override.

public class Test {
  public static void main(String[] args) {
    new Person().printPerson();
    new Student().printPerson();
  }
}

class Student extends Person {
  private String getInfo() {
    return "Student";
  }
}

class Person {
  private String getInfo() {
    return "Person";
  }
  
  public void printPerson() {
    System.out.println(getInfo());
  }
}
Community
  • 1
  • 1
jay
  • 17
  • 6

1 Answers1

0

In the example you have provided,the function getinfo() will not be over-ridden because you have declared the function as private. A private function or variable is accessible or visible only in that particular class.

As a result,when getinfo() is called inside the superclass,it goes to it's own getinfo() and not student's getinfo().

In this case,even if the function was not private,it would not have called student's getinfo() because you are not using the student object to call it.You are simply calling the function.

What could you do?

  • Replace private with protected. This would keep the function a bit secretive and will also make it available among the heirarchy members.

and then a small change:

System.out.println(this.getinfo());
Mathews Mathai
  • 1,707
  • 13
  • 31