封装主要是封装属性,将改显示的显示,将改掩藏的掩藏(例如:一个女孩20岁了,但是她想告诉你她18岁怎么办,通过封装来解决)
编写规则:
定义时,在需要封装的属性前面加上private(私有的),然后进行封装,这里快捷键Ait+Insert--->set and get 就OK了
package javatest1;
public class girl {
private int age; //想要封装,得讲东西弄了成为自己的,所以用private
private double height;
public int getAge() { //get返回值
return age;
} //使用快捷键会默认驼峰模式命名
public void setAge(int age) { //set获取值,可以更改
if(age>30) {
this.age=18;
}
else if(age<30) {
this.age = age;
}
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
package javatest1;
public class test {
public static void main(String[] args) { //输入psvm然后直接tab键
girl g=new girl();
g.setHeight(18);//获取值将g.age=18换为g.setheight
System.out.println(g.getHeight());//将读取值换为g.age换为g.getheight
girl g2=new girl();
g2.setHeight(29);
System.out.print(g2.getHeight());
}
}