1.概述
封装是指隐藏对象的属性和实现细节,仅对外提供公共访问的方式
2.封装好处
- 隐藏实现细节,提供公共的访问方式
- 提高了代码的复用性
- 提高了安全性
3.封装原则
- 将不需要对外提供的内容都隐藏起来
- 把属性隐藏,提供公共方法对其访问
4.封装和private关键字的应用
- 把成员变量用private修饰
- 提供对应的getXxx()方法和setXxx()方法
- private仅仅是封装的一种体现形式,不能说是封装就是私有。
5.this关键字的概述和使用
this关键字特点:代表当前对象的引用
this关键字的应用场景:用来区分同名的成员变量和局部变量。用this调用的就是成员变量
下面的形式就是封装
public class Car {
private String color; //颜色
private int num; //轮胎数
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}