A Question on Encapsulation
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 cl开发者_如何学Goass having public members is not following 100% Encapsulation rule?
Thanks
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.
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.
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.
精彩评论