public class Monster{
String name;
Monster(String name){
this.name = name;
}
public int attack(){
int x = (int)(Math.random() * 5 + 1);
System.out.println(this.name + "who is of class "
+ this.getClass() + "attacks generically - "
+ x + " " + "points damage");
return x;
} public void move(int direction){
switch(direction){
case 1:
System.out.println(this.name + "moving 1 step NORTH.");
break;
case 2:
System.out.println(this.name + "moving 1 step EAST.");
break;
case 3:
System.out.println(this.name + "moving 1 step SOUTH.");
break;
case 4:
System.out.println(this.name + "moving 1 step WEST.");
break;
}
}
}
public class Dragon extends Monster{
Dragon(String name){
this.name = name;
} public int attack(){
int x = 0, n = 0;
if (n < 30){
x = (int)(Math.random() * 50 + 1);
System.out.println(this.name + "who is of class "
+ this.getClass() + "attacks by breathing fire - "
+ x + " " + "points damage");
n++;
}
else{
super.attack();
}
return x;
}
}
String name;
Monster(String name){
this.name = name;
}
public int attack(){
int x = (int)(Math.random() * 5 + 1);
System.out.println(this.name + "who is of class "
+ this.getClass() + "attacks generically - "
+ x + " " + "points damage");
return x;
} public void move(int direction){
switch(direction){
case 1:
System.out.println(this.name + "moving 1 step NORTH.");
break;
case 2:
System.out.println(this.name + "moving 1 step EAST.");
break;
case 3:
System.out.println(this.name + "moving 1 step SOUTH.");
break;
case 4:
System.out.println(this.name + "moving 1 step WEST.");
break;
}
}
}
public class Dragon extends Monster{
Dragon(String name){
this.name = name;
} public int attack(){
int x = 0, n = 0;
if (n < 30){
x = (int)(Math.random() * 50 + 1);
System.out.println(this.name + "who is of class "
+ this.getClass() + "attacks by breathing fire - "
+ x + " " + "points damage");
n++;
}
else{
super.attack();
}
return x;
}
}
Dragon(String name){
this.name = name;
} public int attack(){
int x = 0, n = 0;
if (n < 30){
x = (int)(Math.random() * 50 + 1);
System.out.println(this.name + "who is of class "
+ this.getClass() + "attacks by breathing fire - "
+ x + " " + "points damage");
n++;
}
else{
super.attack();
}
return x;
}
}
先调用父类的构造方法,因为在父类中你重载了初始化构造函数,所以在子类构造方法中需要明确的调用父类的方法 Dragon(String name) {
super(name); //增加这句
this.name = name;
}
public Dragon(String name){
super(name);
}
这样就行了。