简体   繁体   中英

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

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 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM