java-封装

一. 封装的目的

1. 隐藏实现细节
2. 安全

二. 封装的范围

1. 属性的封装,方法的封装
2. 组件的封装
3. 系统的封装

三. 封装的实现

靠权限修饰符来控制可见的范围
## 权限修饰符
1. 可见范围
- private: 本类
- 缺省/省略: 本类,本包
- protected: 本类,本包,其他包子类
- public:任意位置
2. 哪些可以加权限修饰符
- 类,属性,方法,构造器,内部类
3. 分别可以加什么权限修饰符
- 类:缺省或者public
// 如果类前边有public那么必须与源文件名相同
- 属性:四种都可以
- 方法: 四种都可以

四. 属性的封装

- 大多数情况下是private
- 如果属性私有化了,我们会提供get/set方法
- get/set的标准写法
// public void set属性名(数据类型 形参名){
     属性名 = 形参名;
    }
// public 属性的数据类型 get属性名(){
        return 属性名;
    }

五. 方法的封装

大多数情况下是public
When nothing seems to help, I go look at a stonecutter hammering away at his rock, perhaps a hundred times without as much as a crack showing in it. Yet at the hundred and first blow it will split in two, and I know it was not that blow that did it, but all that had gone before. -- Jacob Riis
原文地址:https://www.cnblogs.com/xhwy-1234/p/12373241.html