首先来看两个例子,都是给变量赋值。
theCat.height = 0;
public void setHeight(int ht){
if (ht > 9){
height = ht
}
}
在第二个setter method里,我们通过if语句对ht进行范围限制,从而避免了一些不合理的赋值。 (set boundaries)
Encapsulation rules of thumb
mark your instance variable private, and provide public getters and setters for access control.
Encapsulation Sets Boundaries by forcing other code to go through setter methods.
例子
Encapsulating the GoodDog class (p82)
其他
但是在HW4中使用newNode method新建结点的目的不是为了封装:
The DList class includes a newNode() method whose sole purpose is to call the DListNode constructor. All of your methods that insert a new node should call this method; they should not call the DListNode constructor directly. This will help minimize the number of methods you need to override in Part III.