代码语言:javascript复制
类1
package cn.sxt.oo2;
/**
* 测试封装
* @author 86176
*
*/
public class TestEncapsulation{
private int age;
String name;
protected int height;
public void setAge(int age){
if(age>=1&&age<=130){
this.age=age;
System.out.println("输入年龄成功!");
}else{
System.out.println("请输入正确的年龄!");
}
}
public int Getage(){
return this.age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
void sayAge(){
System.out.println(age);
}
}
类2
package cn.sxt.oo;
import cn.sxt.oo2.TestEncapsulation;
public class Test {
public static void main(String[] args){
TestEncapsulation t1= new TestEncapsulation();
t1.setAge(155);
System.out.println(t1.Getage());
t1.setAge(18);
System.out.println(t1.Getage());
}
}
运行结果: 请输入正确的年龄! 0 输入年龄成功! 18
说明: