0

Why the output of this program is:

person
person

I know that the inheritance means that the subclass take the properties of the superclass, here is the code:

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());
    }
}

I know that getinfo() method is not inherited and not overridden because it is private. But, there is another method in Student class that has the same name and returns Student.

I want to know why that is happening? How JVM works with inheritance exactly?

acm
  • 2,086
  • 3
  • 16
  • 34
  • 2
    Well, the answer is that the `getinfo()` method is not inherited and not overridden because it's private. But you said you know that already. So what's your question exactly? – Dawood ibn Kareem Nov 19 '16 at 10:47
  • Why do you think that `printPerson` would be able to "reach" `Student#getInfo()`? The only method it can "see" (and correctly use) is `Person#getInfo()`. – Tom Nov 19 '16 at 10:48
  • you are hiding the method – Saravana Nov 19 '16 at 10:51
  • @Tom .... Student class able to use printperson() method ,, and inside it System.out.println(getInfo()); ,, theres getinfo() in student class too , i want to know why not using it instead of the methods in person class? – Abdul Rahman Nov 19 '16 at 10:53
  • 1
    second **Person** got printed because , `printPerson()` is inherited by student class and from `printPerson()`, we are calling `getinfo()` , because `printPerson()` method is define inside **Person** class , so `Person#getInfo()` will be called – random_user Nov 19 '16 at 10:55
  • Just because `Student` is able to use methods of `Person` doesn't it also works the other way around. – Tom Nov 19 '16 at 10:56
  • `Person#printPerson` doesn't call `Student#getInfo` because `Person#getInfo` has not been overridden. Because it's private. – Dawood ibn Kareem Nov 19 '16 at 11:10

0 Answers0