Please forgive my code and only focus on the question here :
we know that private field is not inherited and when i am creating 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 . Did my best to post the question accurately.
Rishab Negi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.