private members are not inherited. then how getters and setters able to access private fields in subClass?

1.8k views Asked by At

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

1

There are 1 answers

0
duffymo On BEST ANSWER

When you write code this way, your PrivateFieldTestingUsingGettersAndSetters is not accessing its First 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 to protected in First for class members, it means that classes that extend First can have full access without getters or setters. Classes that don't inherit from First do not have access to protected members.

If you don't supply setters in First, and make First members private final, it makes First immutable. (That's very good for thread safety.)