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
PrivateFieldTestingUsingGettersAndSetters
is not accessing itsFirst
parent's private data members.It is calling public methods on parent
First
that have access to its private data members. The parent class always has access to its state.If you change
private
toprotected
inFirst
for class members, it means that classes that extend First can have full access without getters or setters. Classes that don't inherit fromFirst
do not have access toprotected
members.If you don't supply setters in
First
, and makeFirst
membersprivate final
, it makesFirst
immutable. (That's very good for thread safety.)