超类与子类续作业
package ex3;
class Character {
protected String name;
protected int health;
public Character(String name, int health) {
this.name = name;
this.health = health;
System.out.println("Character构造器第" + (++count) + "次被调用");
}
public String toString() {
return "我叫" + name + ",我的生命值是" + health;
}
private static int count = 0;
}
class Warrior extends Character {
public Warrior(String name, int health) {
super(name, health);
System.out.println("Warrior构造器第" + (++count) + "次被调用");
}
public String toString() {
return "这是一个战士";
}
private static int count = 0;
}
class Mage extends Character {
public Mage(String name, int health) {
super(name, health);
System.out.println("Mage构造器第" + (++count) + "次被调用");
}
public String toString() {
return "这是一个法师";
}
private static int count = 0;
}
class IceMage extends Mage {
public IceMage(String name, int health) {
super(name, health);
System.out.println("IceMage构造器第" + (++count) + "次被调用");
}
private static int count = 0;
}
class FireMage extends Mage {
public FireMage(String name, int health) {
super(name, health);
System.out.println("FireMage构造器第" + (++count) + "次被调用");
}
private static int count = 0;
}
public class Main {
private static void checkCharacter(Character c) {
if (c instanceof Warrior) {
System.out.println("这是一个战士");
} else if (c instanceof Mage) {
System.out.println("这是一个法师");
} else {
System.out.println("这是一个普通角色");
}
}
public static void main(String[] args) {
System.out.println("*****************************");
Character[] characters = new Character[5];
characters[0] = new Character("aa", 100);
characters[1] = new Warrior("bb", 100);
characters[2] = new Mage("cc", 100);
characters[3] = new IceMage("dd", 100);
characters[4] = new FireMage("ee", 100);
System.out.println("*****************************");
System.out.println(characters[3]);
System.out.println("*****************************");
for (Character c : characters) {
checkCharacter(c);
}
}
}