先建立父类Pet,规定属性:昵称,健康值,亲密值,并通过构造方法输入。
吃饭方法:根据健康值的不同做不同操作,吃饭过后,健康值增加
玩耍方法:根据健康值不同做不同操作,玩耍过后,亲密值+10
package PetStore;
public class Pet {
String name;
int health;
int intimacy;
public Pet(String name,int health,int intimacy){
this.name=name;
this.health=health;
this.intimacy=intimacy;
}
public void Eat(){
if(health<90||health==90){
System.out.println("health index <= 90 , eat meat");
this.health+=10;
}
else if(health>90&&health<100){
System.out.println("health index > 90 , eat snacks");
this.health+=1;
}
else{
System.out.println("health index = 100 , the pet is full");
}
}
public void play(){
if(health<50){
System.out.println("the pet is hungry!");
}
else{
System.out.println("it loves to play with you ");
this.intimacy+=10;
}
}
}
创立子类 狗狗
package PetStore;//所属包
public class Dog extends Pet {
String variety;//品种
public Dog(String name, int health, int intimacy,String variety) {
super(name, health, intimacy);
this.variety=variety;
}//运用构造方法完成初始化
public void Eat(){
if(health<90||health==90){
System.out.println("health index <= 90 , eat meat");
this.health+=10;
}
else if(health>90&&health<100){
System.out.println("health index > 90 , eat snacks");
this.health+=1;
}
else{
System.out.println("health index = 100 , the pet is full");
}
}//重写吃饭方法
public void play(){
if(health<50){
System.out.println("the pet is hungry!");
}
else{
System.out.println("it loves to play with you ");
this.intimacy+=10;
}
}//重写吃饭方法
public void Print(){
System.out.println("父类属性:"+"\n昵称:"+super.name+"\n健康值"+super.health+"\n亲密值"+super.intimacy);
System.out.println("自己属性:"+"\n种类:"+this.variety);
}//分别输出父类与子类属性
}
创建子类 猫cat
package PetStore;
public class Cat extends Pet{
String furcolor;//相对于父类,增加毛色
public Cat(String name, int health, int intimacy,String furcolor) {
super(name, health, intimacy);
this.furcolor=furcolor;
}
public void Eat(){
if(health<90||health==90){
System.out.println("health index <= 90 , eat meat");
this.health+=10;
}
else if(health>90&&health<100){
System.out.println("health index > 90 , eat snacks");
this.health+=1;
}
else{
System.out.println("health index = 100 , the pet is full");
}
}
public void play(){
if(health<50){
System.out.println("the pet is hungry!");
}
else{
System.out.println("it loves to play with you ");
this.intimacy+=10;
}
}
public void Print(){
System.out.println("父类属性:"+"\n昵称:"+super.name+"\n健康值"+super.health+"\n亲密值"+super.intimacy);
System.out.println("自己属性:"+"\n毛色:"+this.furcolor);
}
}
主类
package PetStore;
public class PetMain {
public static void main(String args[]){
Pet p = new Pet("petcw",30,90);//创建宠物对象
p.Eat();//调用父类吃饭
p.play();//调用父类玩耍
System.out.println("----------------");
Dog d = new Dog("dogtg",91,60,"jinmao");//创建狗类对象
d.Eat();//调用狗类吃饭
d.play();
d.Print();//调用狗类输出
System.out.println("----------------");
Cat c = new Cat("cattom",100,77,"orange");//创建猫类对象
c.Eat();
c.play();
c.Print();
}
}
运行结果: