用java写面向对象之奥比岛的代码要求包含分支、循环、数组、封装、继承、多态、抽象类、异常处理包含主函数且要有中文注释
时间: 2023-07-04 21:15:05 浏览: 54
好的,我可以帮你解答这个问题。
首先,我们需要了解奥比岛的一些背景知识。奥比岛是一个由魔法和科技共存的神秘岛屿,岛上有许多强大的魔法生物和机械生物。你需要设计一个面向对象的程序来模拟奥比岛的世界。
以下是一个简单的实现,包含了分支、循环、数组、封装、继承、多态、抽象类和异常处理。注释均为中文。
```
// 定义抽象类Creature,所有生物都继承自该类
abstract class Creature {
protected String name; // 生物的名称
protected int health; // 生物的健康值
public Creature(String name, int health) {
this.name = name;
this.health = health;
}
// 生物的行动方法,具体实现由子类实现
abstract void act();
// 生物的受伤方法
public void hurt(int damage) throws HealthOutOfBoundsException {
if (damage < 0) {
throw new IllegalArgumentException("伤害值不能为负数!");
}
this.health -= damage;
if (this.health < 0) {
throw new HealthOutOfBoundsException(this.name + "已经死亡!");
}
}
// 获取生物的名称
public String getName() {
return this.name;
}
// 获取生物的健康值
public int getHealth() {
return this.health;
}
}
// 定义异常类HealthOutOfBoundsException,表示生物的健康值超出范围
class HealthOutOfBoundsException extends Exception {
public HealthOutOfBoundsException(String message) {
super(message);
}
}
// 定义机械生物类Robot,继承自Creature
class Robot extends Creature {
private int power; // 机械生物的攻击力
public Robot(String name, int health, int power) {
super(name, health);
this.power = power;
}
// 机械生物的行动方法
public void act() {
System.out.println(this.name + "发动攻击!");
// TODO: 实现攻击逻辑
}
// 获取机械生物的攻击力
public int getPower() {
return this.power;
}
}
// 定义魔法生物类Wizard,继承自Creature
class Wizard extends Creature {
private int mana; // 魔法生物的魔法值
public Wizard(String name, int health, int mana) {
super(name, health);
this.mana = mana;
}
// 魔法生物的行动方法
public void act() {
System.out.println(this.name + "施放魔法!");
// TODO: 实现魔法逻辑
}
// 获取魔法生物的魔法值
public int getMana() {
return this.mana;
}
}
// 定义奥比岛类ObiIsland
public class ObiIsland {
public static void main(String[] args) {
// 创建两个机械生物和两个魔法生物
Robot r1 = new Robot("机械狗", 100, 10);
Robot r2 = new Robot("机械蜘蛛", 80, 8);
Wizard w1 = new Wizard("火焰法师", 60, 100);
Wizard w2 = new Wizard("冰霜法师", 70, 80);
// 将生物放入一个数组中
Creature[] creatures = {r1, r2, w1, w2};
// 对数组进行循环,让每个生物行动一次
for (int i = 0; i < creatures.length; i++) {
creatures[i].act();
}
// 将每个生物的名称和健康值输出
for (int i = 0; i < creatures.length; i++) {
System.out.println(creatures[i].getName() + "的健康值为:" + creatures[i].getHealth());
}
}
}
```
这个程序包含了一个抽象类Creature,它有两个子类Robot和Wizard,分别代表机械生物和魔法生物。每个生物都有一个行动方法act和一个受伤方法hurt。在act方法中,我们可以实现不同类型生物的不同行为,比如机械生物会发动攻击,魔法生物会施放魔法。在hurt方法中,我们对伤害值进行了异常处理,当伤害值为负数时,会抛出IllegalArgumentException异常;当生物的健康值小于0时,会抛出自定义的HealthOutOfBoundsException异常。在主函数中,我们创建了两个机械生物和两个魔法生物,并将它们放入一个数组中。然后对数组进行循环,让每个生物行动一次。最后,我们输出每个生物的名称和健康值。