SCJA question about encapsulation

I was taking an SCJA practice exam and came across this question...

Which two are true regarding the class diagram...

Customer

-name : String

-phoneNumber : String

+getName() : String

+setName( name : String ) : void

+getPhoneNumber() : String

Obviously answer a. which was "The name attribute is private" was correct, however i incorrectly picked out the next correct answer which turned out to be b."The customer class is well encapsulated".

Whilst this may be a 'small' case of the sour grapes :-) i thought then that to be a well encapsulated class there would also need to be a setter method for the phoneNumber variable, and that seeing as there wasn't in this case it couldn't be well encapsulated, despite being moderately encapsulated.

Does anyone have any thoughts on this? Is there often valid reason to not include setter methods for your private instance variables?

Thanks

[984 byte] By [-Kitsuney-a] at [2007-11-26 13:01:21]
# 1
You will probably get many different answers on this. Some books do even say that having getter/setters is just as evil as making the attribute public.Kaj
kajbja at 2007-7-7 17:02:42 > top of Java-index,Java Essentials,New To Java...
# 2
Think abt final field whose value u'r not going to change or set
AnjanReddya at 2007-7-7 17:02:42 > top of Java-index,Java Essentials,New To Java...
# 3

I am new to the study of OO and Java but you ask for thoughts. I seems that encapsulation does not require that each instance variable have a getter and a setter method, but that the variables be protected (private) and only accessible through the class methods such as getter and setter.

These variables are sometimes called properties of the class and can be read/write, read-only, or write-only. It also seems that if you were to have a read-only property and you provided a setter method to change it, then you have given other classes the ability to change a read-only attribute for you class. The class is encapsulated but it is no longer well-encapsulated because the references are no longer minimized.

In other words it would create a tighter coupling than necessary. I have included a definition for encapsulation which refers to the getter and setter methods and coupling which refers to "well encapsulated".

Encapsulation helps hide implementation behind an interface

Encapsulated code has two features:

1 Instance variables are kept protected (usually with private modifier).

2 Getter and setter methods provide access to instance variables.

Coupling refers to the degree to which one class knows about or uses members of another class.

Loose coupling is the desirable state of having classes that are well encapsulated, minimize references to each other, and limit the breadth of API usage.

David-Ma at 2007-7-7 17:02:42 > top of Java-index,Java Essentials,New To Java...