challenGer
challenGer

Reputation: 13

Calling a function placed in another function that is in another class

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

Upvotes: 0

Views: 167

Answers (2)

vencint
vencint

Reputation: 123

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.

Upvotes: 0

sprinter
sprinter

Reputation: 27946

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.

Upvotes: 2

Related Questions