注意:任何数据类型的father最顶层都是Object
public class GetSetDemo1
{/*
*使用set和get方法进行封装,在set方法里进行判断
*/
private String name; //定义姓名
private int age; //定义年龄
/*
*创建get和set方法
*/
public void setName(String name){
this.name=name; //将参数列表中的name赋值给类中属性
}
public String getName(){
return name;
}
public void setAge(int age){
this.age=age;
}
public Object getAge(){
if(this.age>0 && this.age<=150){ //这里注意在有返回值的时候要考虑 if不成立的时候所以必须有else
return age;
}else{
return "您的年龄不合法";}
}
/*
*在主函数中创建对象进行测试
*/
public static void main(String[] args){
GetSetDemo1 human=new GetSetDemo1();
human.setName("方晓福");
human.setAge(500);
System.out.println(human.getName());
System.out.println(human.getAge());
}
}