Search code examples
javainheritancepolymorphismabstract-classprivate

How does this keyword work in abstract class


I know that private field are not inherited, and when I am creating an object at line #2, the object is being created for Person and then when I set the fatherName, inside the setFatherName() how is this "which is object of person" has the visibility to set Test class private fatherName?

abstract  class  Test {
    private String fatherName ;

    public void setFatherName(String fatherName){
        System.out.println(this.getClass().getSimpleName());
        this.fatherName=fatherName;
    }
    public String getFatherName(){
       return  fatherName;
    }
}
public class Person extends  Test{

    public static void main(String[] args) {
        Test person = new Person(); // #2
        person.setFatherName("Jimmy");
        System.out.println("father name is : " +person.getFatherName());

    }
}

Output :

Person
father name is : Jimmy

I understand the context that I am indirectly doing it with a setter, but how does this keyword work here in abstract class since object is Person?


Solution

  • It works because the setter is inherited, which is marked as public. The variables are actually "inherited" too (meaning that they have a place allocated in the memory), even if they are marked as private. You just cannot directly access them from the child class.

    Accessing them using a public method, as you do here, is allowed. The setter you are calling is actually called inside the superclass. If you had overridden it, you wouldn't have access to this.fatherName inside the child class. You should have delegated the setting logic to the parent.

    But using a setter should work. Better to mark your field as protected, though, in order to respect encapsulation. I consider that inside the class hierarchies, direct access to the variable should be prioritized over public methods, while setters should be used for access from outside.