概念:
将类里面一些隐蔽的信息用特殊的方法隐藏起来,不允许外部程序随意访问,而是通过该类设定的特殊方法来实现对这些隐蔽信息的访问和操作。
好处:
1.只能通过规定的方法访问
2.方便修改和实现
封装步骤:
1.修改属性的可见性
2.创建getter/setter方法
3.在getter/setter方法中加入属性控制语句
案列:
public class House {
private float length;//添加修饰符private
private float wide;//添加修饰符private
private float hight;//添加修饰符private
//创建getter和setter方法
//返回属性值
public float getLength(){
return length;
}
//通过setter方法给属性赋值
public void setLength(float length){
this.length=length;
}
}
public class HouseNature {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建对象
House bo = new House();
//通过setLength方法给属性赋值
bo.setLength(300f);
//通过getLength方法获得属性值
System.out.print(bo.getLength());
}
}
eclipse中自带的一个封装方法:
选中需要生成的属性值: