您的位置:首页 > 编程语言 > Java开发

Thinking in java -6 隐藏的实现 Hidden implementation

2017-06-14 21:47 197 查看

1.从不同角色的角度看类的存在

It is helpful to break up the playing field into class creators (those who create new data types) and client programmers (the class consumers who use the data types in their applications).

The goal of the class creator is to build a class that exposes only what’s necessary to the client programmer and keeps everything else hidden. Why? because if it’s hidden, the client programmer can’t access it, which means that the class creator can change the hidden portion at will without worrying about the impact on anyone else. The hidden portion usually represents the tender insides of an object that could easily be corrupted by a careless or uniformed client programmer, so hiding the implementation reduces program bug.

作为类的使用者和类的创建者而言他们所需要的功能是不同的(类的使用者只需将类作为一种新的数据类型使用,并不关心其实现细节;类的创建者则需要精心设计类的具体接口,如类的方法),所需要提供的功能也是不同的。

如此设计有利于数据隐藏,防止类数据遭到破坏,提高代码鲁棒性。

2.实现手段

Java uses three explicit keywords to set the boundaries in a class: public, private and protected.

通过使用public/private/protected关键字及默认不加任何修饰手段方法,修饰类的方法和变量来设置访问界限。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息