你能解释一下关于封装的事情吗?
In response to What is your longest-held programming assumption that turned out to be incorrect? question, one of the wrong assumptions was:
That private member variables were
private to the instance and not the
class.
(Link)
I couldn't catch what he's talking about, can anyone explain what is the wrong/right about that with an example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样。正如您所看到的,私有并不能保护实例成员不被另一个实例访问。
顺便说一句,只要您小心一点,这并不全是坏事。
如果 private 不能像上面的例子那样工作,那么编写 equals() 和其他此类方法就会很麻烦。
Like this. As you can see private doesn't protect the instance member from being accessed by another instance.
BTW, this is not all bad as long as you are a bit careful.
If private wouldn't work like in the above example, it would be cumbersome to write equals() and other such methods.
这相当于 Michael Borgwardt 的答案,当您无法 能够访问另一个对象的私有字段:
现在这对 Ruby 程序员来说很熟悉,但我在 Java 中这样做已经有一段时间了。我不喜欢依赖对另一个对象的私有字段的访问。请记住,其他对象可能属于子类,子类可以将值存储在不同的对象字段中,或者存储在文件或数据库等中。
Here's the equivalent of Michael Borgwardt's answer for when you are not able to access the private fields of the other object:
Nowadays this is familiar to Ruby programmers but I have been doing this in Java for a while. I prefer not to rely on access to another object's private fields. Remember that the other object may belong to a subclass, which could store the value in a different object field, or in a file or database etc.
示例代码 (Java):
如果“私有成员变量对于实例而言是私有的”这一假设是正确的,则标记的行将导致编译器错误,因为
other.value
字段是私有的并且是与调用 equals() 方法的对象不同的对象。但由于在 Java(以及大多数其他具有可见性概念的语言)中,
private
可见性是针对每个类的,因此允许MutableInteger
的所有代码访问该字段,因此无关紧要使用什么实例来调用它。Example code (Java):
If the assumption "private member variables are private to the instance" were correct, the marked line would cause a compiler error, because the
other.value
field is private and part of a different object than the one whoseequals()
method is being called.But since in Java (and most other languages that have the visibility concept)
private
visibility is per-class, access to the field is allowed to all code of theMutableInteger
, irrelevant of what instance was used to invoke it.