bragboy
bragboy

Reputation: 35562

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 class having public members is not following 100% Encapsulation rule?

Thanks

Upvotes: 4

Views: 878

Answers (4)

Doug
Doug

Reputation: 5328

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!

Upvotes: 3

Bill the Lizard
Bill the Lizard

Reputation: 406035

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.

Upvotes: 6

Robben_Ford_Fan_boy
Robben_Ford_Fan_boy

Reputation: 8728

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.

Upvotes: 0

andyczerwonka
andyczerwonka

Reputation: 4260

Correct. No data/state in the class should be exposed unless it's a final value.

Upvotes: 0

Related Questions