-
类的数据成员尽量private
-
提供相应的get/set方法来访问相关属性,这些方法通常是public修饰的,以提供对属性的赋值与读取操作(注意:boolean变量的get方法是is开头!)。
-
一些只用于本类的辅助性方法可以用private修饰,希望其他类调用的方法用public修饰。
package private4element;
/*
* 数据成员私有化
* set/get方法
*/
public class person {
private int id;
private String name;
private int age;
private boolean man;
//set/get方法可里利用eclipse编译器可自动生成
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
if(age >=1 && age <= 150)
this.age = age;
else {
System.out.println("请正确输入年龄!");
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isMan() {
return man;
}
public void setMan(boolean man) {
this.man = man;
}
}
package private4element;
public class person4Encapsulation {
public static void main(String[] args) {
person p = new person();
p.setName("黑凤梨");
System.out.println("姓名:" + p.getName());
p.setAge(18);
p.setAge(-18);
System.out.println("年龄:" + p.getAge());
}
}
JavaBean的封装
只含有set/get方法