i have read from almost every source that private members are not inherited. Then how getters and setters of these private fields able to access private fields in subClass?
here is my code which is working fine.
class First{
private String first;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
}
public class PrivateFieldTestingUsingGettersAndSetters extends First{
private String second;
public String getSecond() {
return second;
}
public void setSecond(String second) {
this.second = second;
}
public static void main(String[] args){
PrivateFieldTestingUsingGettersAndSetters ob1=new PrivateFieldTestingUsingGettersAndSetters();
ob1.setFirst("first");
ob1.setSecond("second");
System.out.println(ob1.getFirst());
System.out.println(ob1.getSecond());
}
}
Output is: first second
When you write code this way, your
PrivateFieldTestingUsingGettersAndSettersis not accessing itsFirstparent's private data members.It is calling public methods on parent
Firstthat have access to its private data members. The parent class always has access to its state.If you change
privatetoprotectedinFirstfor class members, it means that classes that extend First can have full access without getters or setters. Classes that don't inherit fromFirstdo not have access toprotectedmembers.If you don't supply setters in
First, and makeFirstmembersprivate final, it makesFirstimmutable. (That's very good for thread safety.)