1.封装的实现方法
1)将属性进行私有化private
2)提供一个公共的set方法,用于对属性判断并赋值;
3)提供一个公共的get方法,用于获取属性的值;
2.使用有参构造器可以“绕开”set方法“防护的机制”;
class Person {
...
public Person (String name, int age, double salary){
this.name = name;
this.age = age;
this.salary = salary;
}
}
3.可以将set方法写在构造器中,依然可以起到防护验证的作用
class Person {
...
public Person (String name, int age, double salary){
//this.name = name;
//this.age = age;
//this.salary = salary;
setName(name);
setAge(age);
setSalary(salary);
}
}