JAVA的封装机制
面向对象三大特征:
——封装
——继承
——多态
封装步骤:
1、所有属性私有化,用private关键字进行修饰,修饰的数据只能在本类中访问。
2、对外提供简单的操作入口,必须通过这些入口进行访问。
一个属性通常有两种访问形式:
——读取该属性的值:读取get
——修改该属性的值:修改set
get方法命名规范:
public 数据类型 get+变量名(首字母需大写)(){
return 变量名;
}
set方法命名规范:
public void set+变量名(首字母需大写)(数据类型 变量名){
this.变量名 = 变量名;
}
public class Customer {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
iif(age < 0) { //通过在setter方法中设立过滤条件可以筛选出想要的数据范围
System.out.println("数据非法");
return;
}
this.age = age;
}
public class Customertest {
public static void main(String[] args){
Customer a = new Customer();
System.out.println(a.getAge()); //0
a.setAge(-20); //数据非法
System.out.println(a.getAge()); //0
a.setAge(20);
System.out.println(a.getAge()); //20
}
}