Reputation: 1069
This is a piece of code that I have that I'm testing right now, and I noticed that when I change public to private on the getInfo() method in Person, both Student().printPerson() & Person().printPerson() print out "Person". However, when it's public, "Student" is displayed. Can someone explain this? Why is it that the private modifier disallows access to the getInfo method from Student?
new Student().printPerson();
new Person().printPerson();
}
}
class Student extends Person {
public Student(){
System.out.println("student invoked") ;
}
public String getInfo() {
return "Student";
}
}
class Person {
public Person(){
System.out.println("person invoked");
}
private String getInfo() {
return "Person";
}
public void printPerson() {
System.out.println(getInfo());
}
Upvotes: 1
Views: 61
Reputation: 887215
public
(or protected
) method in Java are always virtual.
This means that if a derived class overrides the method, calls made through the base class will call the derived class (if the object is actually an instance of the derived class).
When your base method is public
, this happens, and calling it from printPerson()
calls the overriding derived version.
When it's private
, it is not virtual, so calls from the base class always call the base version (since it doesn't know about the derived class' method).
Upvotes: 5