java代码使用重写来优化电子宠物系统

需求说明: 使用方法重写优化电子宠物系统,实现如下效果: 依据图片可知,我们可以建立三个类,一个是pet类,一个是dog类,还有一个penguin类,且pet类是dog类和penguin类的父类。

实现代码如下:

//Pet类

public class Pet { private String name;//名字 private int health;//健康值 private int love;//亲密值

//show方法
public void show(){
    System.out.println("宠物的自白:
我的名字叫:"+name+",我的健康值是:"+health+",我和主人的亲密度是"+love);
}

//宠物的构造方法
public Pet(String name, int health, int love) {
    this.name = name;
    this.health = health;
    this.love = love;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getHealth() {
    return health;
}

public void setHealth(int health) {
    this.health = health;
}

public int getLove() {
    return love;
}

public void setLove(int love) {
    this.love = love;
}

}

//Dog类

public class Dog extends Pet{ private String type;//宠物的种类

//方法的重写
@Override
public void show() {
    super.show();
    System.out.println("我是一只"+type+"犬");
}

//狗狗的构造方法
public Dog(String name, int health, int love, String type) {
    super(name, health, love);
    this.type = type;
}



public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

}

//penguin类

public class Penguin extends Pet{ private String sex;//企鹅的性别

//show方法


@Override
public void show() {
    super.show();
    System.out.println("我的性别是:"+sex);
}

//构造方法
public Penguin(String name, int health, int love, String sex) {
    super(name, health, love);
    this.sex = sex;
}

public String getSex() {
    return sex;
}

public void setSex(String sex) {
    this.sex = sex;
}

}

//测试类

public class Test1 {

public static void main(String[] args) {

    showInfo(new Dog("欧欧",100,0,"雪瑞纳"));
    showInfo(new Penguin("楠楠",100,0,"Q妹"));


}

//在方法传参时,完成向上转型
private static void showInfo(Pet pet){
    pet.show();
}

}

经验分享 程序员 微信小程序 职场和发展