public class Dog {
private String name = "无名氏";
private int health = 100;
private int love = 0;
private String strain="聪明的拉不拉多犬";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
if (health>100||health<0) {
this.health = 40;
System.out.println("健康值在0和100之间,默认值40");
}else {
this.health = health;
}
}
public int getLove() {
return love;
}
public void setLove(int love) {
this.love = love;
}
public String getStrain() {
return strain;
}
public void setStrain(String strain) {
this.strain = strain;
}
/**
* 输出狗狗的信息
*/
public void print(){
System.out.println("宠物的自白:\n我的名字叫" + this.name + ",健康值是" + this.health
+ ",和主人的亲密度是" + this.love + ",我是一只" + this.strain + "。");
}
}
public class Test {
/**
* 测试封装类
* @param args
*/
public static void main(String[] args) {
Dog dog=new Dog();
dog.setHealth(300);
dog.setName("欧欧");
System.out.println("名字叫"+dog.getName());
System.out.println("健康值是"+dog.getHealth());
System.out.println();
dog.print();
}