Question

The class properties must be accessible using get, set, is (can be used for boolean properties instead of get), and other methods (so-called accessor methods and mutator methods) according to a standard naming convention.

Doesn't this break the rule of encapsulation? After all if every private property has a getter/setter doesn't that make it not encapsulated?

Or do you have to use at least one for each property? either set, get, or both but never none?

Était-ce utile?

La solution

You are confusing the term "property" with "instance variable". A property is that which you can set and/or get from outside the class. In Java, a property is created by having a private instance variable used through accessor methods (setter and/or getter). In JavaBeans, you can have private instance variables without a getter or a setter, but that makes it just an instance variable, not a property.

Autres conseils

You must atleast have setter for your property to avoid null value when you access the value.

Yes though the property is private your set/get methods are public and hence you are allowing others to access your property. But in your setter/getter method you can add your own conditions to keep your property encapsulated rather exposing it public to all depending upon your requirement.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top