java 子 class 如何继承受访问保护的父字段?
How does a java child class inherit access-protected parent fields?
这是一个新手问题,但我用谷歌搜索了一下,似乎找不到答案。
假设我有一个 class 人:
class Person {
private String SSN;
//blah blah blah...
}
然后我创建一个子class OldMan:
class OldMan inherits Person {
//codey stuff here...
public void setSSN(String newSSN) {
SSN = newSSN;
}
}
看来我实际上无法更改 Person 的私有字段。我的印象是,当 OldMan 继承 Person 时,它会拥有自己的私有变量副本。看起来实际发生的事情是当我创建一个 OldMan 对象时,它创建了 SSN 字段但是......它以某种方式属于 Person 对象?
我知道我可以让 SSN 受到保护,但这是最佳做法吗?这里到底发生了什么,如何创建一个父 class 来保护重要字段的访问权限,而不保护它们免受子 classes 的影响?
你可以这样做,
class Person {
private String SSN;
//blah blah blah...
public String getSSN() {
return SSN;
}
public void setSSN(String sSN) {
SSN = sSN;
}
}
public class OldMan extends Person {
//codey stuff here...
public void setSSN(String newSSN) {
super.setSSN(newSSN);
}
}
It seems like what's actually happening is that when I create an OldMan object, it creates the SSN field but... it somehow belongs to a Person object??
是的。确切地。
I realize I can just make SSN protected, but is that a best practice?
没错。这就是 protected 的工作原理,您可以放心使用它。
What's actually going on here, and how can create a parent class that will have important fields access protected, without protecting them from child classes?
正如你刚才所说,让他们保护起来,现在他们只能通过儿童和包裹中的人访问。
这是一个新手问题,但我用谷歌搜索了一下,似乎找不到答案。
假设我有一个 class 人:
class Person {
private String SSN;
//blah blah blah...
}
然后我创建一个子class OldMan:
class OldMan inherits Person {
//codey stuff here...
public void setSSN(String newSSN) {
SSN = newSSN;
}
}
看来我实际上无法更改 Person 的私有字段。我的印象是,当 OldMan 继承 Person 时,它会拥有自己的私有变量副本。看起来实际发生的事情是当我创建一个 OldMan 对象时,它创建了 SSN 字段但是......它以某种方式属于 Person 对象?
我知道我可以让 SSN 受到保护,但这是最佳做法吗?这里到底发生了什么,如何创建一个父 class 来保护重要字段的访问权限,而不保护它们免受子 classes 的影响?
你可以这样做,
class Person {
private String SSN;
//blah blah blah...
public String getSSN() {
return SSN;
}
public void setSSN(String sSN) {
SSN = sSN;
}
}
public class OldMan extends Person {
//codey stuff here...
public void setSSN(String newSSN) {
super.setSSN(newSSN);
}
}
It seems like what's actually happening is that when I create an OldMan object, it creates the SSN field but... it somehow belongs to a Person object??
是的。确切地。
I realize I can just make SSN protected, but is that a best practice?
没错。这就是 protected 的工作原理,您可以放心使用它。
What's actually going on here, and how can create a parent class that will have important fields access protected, without protecting them from child classes?
正如你刚才所说,让他们保护起来,现在他们只能通过儿童和包裹中的人访问。