Java中关于继承的题目3

3.某公司要开发新游戏,请用面向对象的思想,设计游戏中的蛇怪和蜈蚣精 设定
1)蛇怪类:
属性包括:怪物名字,生命值,攻击力
方法包括:攻击,移动(曲线移动),补血(当生命值<10 时,可以补加 20 生命值)
2)蜈蚣精类:
属性包括:怪物名字,生命值,攻击力方法包括:攻击,移动(飞行移动) 要求
1)分析蛇怪和蜈蚣精的公共成员,提取出父类—怪物类
2)利用继承机制,实现蛇怪类和蜈蚣精类
3)攻击方法,描述攻击状态。内容包括怪物名字,生命值,攻击力
4)编写测试类,分别测试蛇怪和蜈蚣精的对象及相关方法
5)定义名为 mon 的包存怪物类,蛇怪类,蜈蚣精类和测试类运行效果

怪物父类

class Monster {
     private String name;
     private int health;
     private int attack;

    public Monster() {

    }

    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 getAttack() {
        return attack;
    }

    public void setAttack(int attack) {
        this.attack = attack;
    }

    public Monster(String name, int health, int attack) {
        this.name = name;
        this.health = health;
        this.attack = attack;
    }

    //创建一个怪物类的攻击方法
    public void Attack(){
         System.out.println("怪物"+name+"展开攻击"+"\n"+"当前生命值是:"+health+"\n"+"攻击力是:"+attack);
    }

}

蛇精怪类

class Basilisk extends Monster {
    public Basilisk() {   //无参构造
    }

    Basilisk(String name, int health, int attack) { //有参构造
        super(name, health, attack);   //由于父类的变量是私有的,直接获取不到,需要通过调用父类的构造方法进行复制
        super.Attack();              //调用父类的攻击方法
    }

    public void Blood() {          //蛇精的独有方法
        if (getHealth() < 10) {
            setHealth(getHealth() + 20);   //由于父类的变量私有的,子类无法继承,可以通过调用父类的get和set方法对生命值进行修改
            System.out.println("实施大蛇补血术。。。。,当前生命值是:" + getHealth());
        }
    }

    public void Move() {
        System.out.println("我是蛇怪,我走S路线");
    }
}

蜈蚣类

class Centipede extends Monster {
    public Centipede() {
    }

    public Centipede(String name, int health, int attack) {
        super(name, health, attack);
        super.Attack();
    }

    public void Move() {
        System.out.println("我是蜈蚣精,御风飞行");
    }

}

编写测试类,传值进行测试

public class game {
    public static void main(String[] args) {
        Basilisk b1 = new Basilisk("蛇精甲", 5, 20);
        b1.Blood();
        b1.Move();
        System.out.println("===================");
        Centipede c1 = new Centipede("蜈蚣乙", 60, 15);
        c1.Move();

    }
}
posted @ 2024-09-25 09:36  你的镁偷走了我的锌  阅读(28)  评论(0)    收藏  举报