Encapsulation in Java中的封装

首先来看两个例子,都是给变量赋值。

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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容