
[英]Why private/protected members must originate from the same class for type compatibility?
[英]Why protected and private attributes are accessible by same class rather than by the same object?
例如,我们有类Man
如果Man.age
受到保护,那么我不明白为什么chuckNorris
(类Man
实例)可以更改对象jackBauer
(类Man
另一个实例)的protected / private属性age
。 他不应该这样做(IMO)。
在我的脑海里,一个保护/私有属性的值应该是只属于对象本身,而不是类 ...
我想要一些解释,我很困惑。
马蒂厄是对的。 cuckNorris可以做jackBauer.age
但是没有问题。 如果您在Man中引用Man实例属性,那意味着您正在编写Man类,因此您知道自己在做什么。
问题是如果你传给我Man类,我可以访问Man属性而不知道Man类是如何编码的。
Setter和getter可能正在做一些我不知道的业务逻辑,我不需要知道。 但编码Mam的人确实知道。
考虑这个Java类:
public class Base {
private int a
protected int b;
public Base(int a,int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
}
...
Base foo = new Base(1,2);
Base bar = new Base(3,4);
没有办法(可能除了通过脏反射) foo
实例可以更改bar
的protected或private变量
如果你愿意,你可以允许它,
public class Base {
private int a
protected int b;
public Base(int a,int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public void changeB(int newB,Base other) {
other.b = newB;
}
}
...
Base foo = new Base(1,2);
Base bar = new Base(3,4);
foo.changeB(5,bar);
你不能保护changeB
方法不改变other
对象[*]内的东西,你只需要小心程序的功能。 对于某些语言,您可以将other
参数标记为不可更改,但不是Java中 - 我认为这不是什么大问题。
[*}你可以通过将Base
所有字段标记为final,尽管在构造对象之后甚至实例本身都不能更改成员。
私有属性只能通过类中的方法访问。 受保护的属性仅在后代类中是accessibe。 因此,对象jackbauer不能修改私人或受保护的对象chuckNorris类Man。 希望这会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.