0

I couldn't grasp the idea why the codes below prints console Person twice. I thought it should have been Person and Student. When getInfo() inside printPerson() is called through "a" object, why is the one inside Person class being invoked and why is the one in the Student class not invoked? Thanks in advance.

class deneme{
     public static void main(String[] args) {
        Person b = new Person();
        b.printPerson();
        Student a = new Student();
        a.printPerson();
    }
}

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

 }

class Person{

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

     public void printPerson() {
        System.out.println(getInfo());
    }
}
challenGer
  • 13
  • 4

2 Answers2

2

You have attempted to override a private method. That is not possible. See Override "private" method in java for details. Because Student is not able to see Person.getInfo Java assumes you are declaring a new method.

If you make getInfo public you will find that Student is printed instead.

This is a good argument for using the @Override annotation before any methods that you are intending to override a superclass's method. It isn't just documentation - it can avoid subtle errors by letting your IDE warn.

sprinter
  • 27,148
  • 6
  • 47
  • 78
  • Actually i knew private methods cannot be overridden and that i declare a new method. But the point where i got confused is I am calling printPerson method in main method through an object of Student class, isn't that strange that getInfo method in Student is not invoked even though I called printPerson method in the main method through a Student class object? – challenGer Feb 20 '20 at 22:30
  • `Person.printPerson` knows that `getInfo` is private and, therefore, not overridable. So the actual type of `this` is irrelevant at that point - it must call the local private `getInfo` – sprinter Feb 20 '20 at 22:59
0

I think that is because Person.getInfo() is private and you cannot override private methods, so a.printPerson() will actually call its own getInfo(). Always annotate methods you want to override with @Override; the compiler will throw an error if there was no method found in the parent class to override.
If you want to make Person.getInfo() private to other classes but still want to override it, simply make it protected.

vencint
  • 113
  • 1
  • 9