关于封装的一个问题
我知道封装是将成员及其行为绑定在一个实体中。这让我觉得成员必须保持私密。这是否意味着具有公共成员的类不遵循 100% 封装规则?
谢谢
I know that encapsulation is binding the members and its behavior in one single entity. And it has made me think that the members have to be private. Does this mean if a class having public members is not following 100% Encapsulation rule?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
封装既是数据捆绑也是数据隐藏。 Java 允许您公开数据,但如果您选择这样做,则应该有一个很好的理由。成员变量应默认设置为私有,并且仅在绝对必要时才提升为更高的可见性。
Encapsulation is both data bundling and data hiding. Java allows you to expose data, but you should have a very good reason for it if you choose to do so. Member variables should be made private as a default, and only promoted to higher visibility if absolutely necessary.
这意味着内部字段(您想要封装在类中)应该是私有的,并且只能通过 getter、setter、属性等公开。隐藏和捆绑类的内部成员,并通过特定框架 java 中提供的某些方法控制访问(getters setters),.net(属性)等是封装。
并回答您的问题,为什么要实现封装?这样您就可以控制对类的内部成员的访问。例如,如果您有一个整数字段,您只想将其设置为 1 - 10 范围内的值。如果您直接公开该整数字段,则没有机制可以阻止使用者将值设置为超出您所需的范围。但是,您可以通过封装来实现此目的,通过 setter 或属性公开内部 int 字段,从而允许您在 setter 或属性中添加验证代码,以“监管”为内部字段设置哪些值。
享受!
It means that internal fields (that you want to encapsulate in your class) should be private and only exposed via getter, setters, property's etc. Hiding and bundling the internal members of your class and controlling access through some method provided in your particular framework java (getters setters), .net (properties) etc is encapsulation.
And to answer your question why would you implement encapsulation? Well it so that you can control access to an internal member of you class. For instance if you had an integer field that you only wanted set to values in the range from 1 - 10. If you exposed the integer field directly there is no mechanism to keep a consumer from setting values outside your desired range. However, you can achieve this through encapsulation by exposing your internal int field though a setter or property thus allowing you to add validation code within the setter or property to "police" what values get set to your internal field.
Enjoy!
正确的。除非是最终值,否则不应公开类中的任何数据/状态。
Correct. No data/state in the class should be exposed unless it's a final value.
几乎 - 如果您认为一个对象具有状态,那么现在任何人都可以在您不知情的情况下修改您的对象的状态。至少使用 setter 方法你可以更好地控制对象的状态。
Pretty much - if you think of an object as having state, now anybody can modify the state of your object without you knowing. At least with setter methods you can better control the state of the object.