为什么受保护的属性和私有属性可以由同一类而不是同一对象访问?
例如,我们有类 Man
如果 Man.age
受到保护,那么我不明白为什么 chuckNorris
(类 Man.age
的实例>Man)可以更改对象jackBauer
(类Man
的另一个实例)的受保护/私有属性age
。他不应该这样做(IMO)。
在我看来,受保护/私有属性的值应该只属于对象本身,而不是类......
我我想需要一些解释,我很困惑。
For example, we have the class Man
If Man.age
is protected, then I don't see why chuckNorris
(instance of class Man
) can change the protected/private attribute age
of the object jackBauer
(another instance of class Man
). He shouldn't be able to do that (IMO).
In my mind, the value of a protected/private attribute is supposed to belong only to the object itself, not the class...
I need some explanation I think, I'm confused.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
马修是对的。 cuckNorris 可以做 jackBauer.age
但这没有问题。如果您在 Man 内部引用 Man 实例属性,则意味着您正在编写 Man 类,因此您知道自己在做什么。
问题是,如果您将 Man 类传递给我,我就可以在不知道 Man 类如何编码的情况下访问 Man 属性。
setter 和 getter 可能正在执行一些我不知道也不需要知道的业务逻辑。但为妈妈编写代码的人确实知道这一点。
Matthieu is right. cuckNorris can do jackBauer.age
But there is no problem on that. If you are referencing Man instance attributes inside Man, that means you are coding Man class, so you know what you are doing.
The problem would be if you pass me that Man class and I could access the Man attributes with out knowing how Man class is coded.
Setters and getters may be doing some business logic that I don't know and I don't need to know. But the one who coded Mam does know.
考虑这个 Java 类:
foo
实例没有办法(也许除了通过脏反射)可以更改bar
中的受保护或私有变量,如果您愿意,您可以允许这样做,
您无法保护
changeB
方法不更改other
对象 [*] 内的内容,您只需小心程序的行为即可。对于某些语言,您可以将other
参数标记为 unchangeable ,但在 Java 中不行 - 我认为这没什么大不了的。[*} 您可以通过将
Base
的所有字段标记为 Final,尽管在构造对象后,甚至实例本身也无法更改成员。Consider this Java class:
There is no way(maybe except via dirty reflection) the
foo
instance can change the protected or private variable inbar
You might allow it to if you want,
You can't protect the
changeB
method from altering stuff inside theother
object [*], you just have to be careful about what your program does. With some languages you could have marked theother
argument as unchangable , but not in Java - I don't find it a big deal.[*} You could, by marking all the fields of
Base
as final, though then not even the instance itself could change the members after the object has been constructed.私有属性只能通过类中的方法访问。
受保护的属性只能在后代类中访问。因此,对象 jackbauer 不能修改 Man 类的对象 chuckNorris 中的任何私有或受保护的内容。希望这会有所帮助
A private attribute is accessible only by method in the class.
A protected attribute is accessibe in descendant class only. Therefore an object jackbauer can't modify anything private or protected in an object chuckNorris of class Man. Hope this would help