继承课后作业
课后作业代码
Main.java
点击查看代码
package ex3;
import javafx.geometry.HPos;
public class Main {
static int count=1;
static int Mcount=1;
static int Wcount=1;
static int Icount=1;
static int Fcount=1;
private static void checkCharacter(Character c) {
if (c instanceof Warrior){
System.out.println("这是一个战士");
}else if (c instanceof Mage){
System.out.println("这是一个法师");
} else if (c instanceof IceMage) {
System.out.println("这是一个法师");
}else if (c instanceof FireMage){
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);
}
}
}
Character.java
点击查看代码
package ex3;
public class Character {
String name;
int HP;
public Character(String name, int HP) {
this.name = name;
this.HP = HP;
System.out.println("Character构造器第"+Main.count+"次被调用");
Main.count++;
}
public String toString() {
return "我叫" + name + ','+
", HP=" + HP
;
}
}
Warrior.java
点击查看代码
package ex3;
public class Warrior extends Character{
public Warrior(String name, int HP) {
super(name, HP);
System.out.println("Warrior构造器第"+Main.Wcount+"次被调用");
Main.Wcount++;
}
public String toString() {
return "我叫" + name + ','+
", HP=" + HP
;
}
}
Mage.java
点击查看代码
package ex3;
public class Mage extends Character{
public Mage(String name, int HP) {
super(name, HP);
System.out.println("Mage构造器第"+Main.Mcount+"次被调用");
Main.Mcount++;
}
public String toString() {
return "我叫" + name + ','+
", HP=" + HP
;
}
}
FireMage.java
点击查看代码
package ex3;
public class FireMage extends Mage{
public FireMage(String name, int HP) {
super(name, HP);
System.out.println("FirMage构造器第"+Main.Fcount+"次被调用");
Main.Fcount++;
}
public String toString() {
return "我叫" + name + ','+
", HP=" + HP
;
}
}
IceMage.java
点击查看代码
package ex3;
public class IceMage extends Mage {
public IceMage(String name, int HP) {
super(name, HP);
System.out.println("IceMage构造器第"+Main.Icount+"次被调用");
Main.Icount++;
}
@Override
public String toString() {
return "我叫" + name + ','+
", HP=" + HP
;
}
}
运行结果:
IceMage构造器第1次被调用
Character构造器第5次被调用
Mage构造器第3次被调用
FirMage构造器第1次被调用
我叫dd,, HP=100
这是一个普通角色
这是一个战士
这是一个法师
这是一个法师
这是一个法师
Process finished with exit code 0``