[英]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?
那么这些私有字段的getter和setter如何能够访问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. 当您以这种方式编写代码时,您的
PrivateFieldTestingUsingGettersAndSetters
不会访问其First
父级的私有数据成员。
It is calling public methods on parent First
that have access to its private data members. 它呼吁家长公共方法
First
可以访问它的私有数据成员。 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. 如果您将Class成员的“
private
更改为“ First
protected
,则意味着扩展First的类可以具有完全访问权限,而无需getter或setter。 Classes that don't inherit from First
do not have access to protected
members. 不从
First
继承的类无权访问protected
成员。
If you don't supply setters in First
, and make First
members private final
, it makes First
immutable . 如果您不提供
First
设置者,并且将First
成员private final
,则First
身份不变 。 (That's very good for thread safety.) (这对于线程安全性非常好。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.