以僵尸为主体,写一个java代码
时间: 2024-03-23 08:38:28 浏览: 12
好的,以下是一个简单的Java代码示例,以僵尸为主体:
首先,我们创建一个抽象类Zombie作为父类,包含一些共同属性和方法:
```
public abstract class Zombie {
protected int health; // 僵尸的生命值
protected int speed; // 僵尸的移动速度
public Zombie(int health, int speed) {
this.health = health;
this.speed = speed;
}
public abstract void attack(); // 攻击方法
public abstract void move(); // 移动方法
}
```
接下来,我们创建两个子类,分别为FastZombie和SlowZombie,它们继承了Zombie类,并实现了相应的攻击和移动方法:
```
public class FastZombie extends Zombie {
public FastZombie(int health, int speed) {
super(health, speed);
}
@Override
public void attack() {
System.out.println("FastZombie attacks with speed!");
}
@Override
public void move() {
System.out.println("FastZombie moves quickly!");
}
}
public class SlowZombie extends Zombie {
public SlowZombie(int health, int speed) {
super(health, speed);
}
@Override
public void attack() {
System.out.println("SlowZombie attacks with strength!");
}
@Override
public void move() {
System.out.println("SlowZombie moves slowly!");
}
}
```
接下来,我们可以创建一个测试类,测试不同类型的僵尸对象的攻击和移动方法:
```
import java.util.Scanner;
public class ZombieGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the type of zombie (Fast or Slow):");
String type = scanner.nextLine();
Zombie zombie = null;
if (type.equalsIgnoreCase("Fast")) {
zombie = new FastZombie(100, 20);
} else if (type.equalsIgnoreCase("Slow")) {
zombie = new SlowZombie(150, 10);
}
if (zombie != null) {
zombie.move();
zombie.attack();
} else {
System.out.println("Invalid zombie type!");
}
}
}
```
以上代码演示了如何通过命令行接收数据,并根据数据创建不同类型的僵尸对象,然后测试它们的攻击和移动方法。