例:某公司要开发新游戏,请用面向对象的思想,设计游戏中的蛇怪和蜈蚣精设定
1) 蛇怪类:
属性包括:怪物名字,生命值,攻击力
方法包括:攻击,移动(曲线移动),补血(当生命值<10时,可以补加20生命值)
2) 蜈蚣精类:
属性包括:怪物名字,生命值,攻击力
方法包括:攻击,移动(飞行移动)
要求
1) 分析蛇怪和蜈蚣精的公共成员,提取出父类—怪物类
2) 利用继承机制,实现蛇怪类和蜈蚣精类
3) 攻击方法,描述攻击状态。内容包括怪物名字,生命值,攻击力
4) 编写测试类,分别测试蛇怪和蜈蚣精的对象及相关方法
5) 定义名为mon的包存怪物类,蛇怪类,蜈蚣精类和测试类
父类:
package mon;
public class Monster {
public String mname;
public int hp;
public int atk;
public void attack() {
System.out.println("攻击");
}
public void move() {
System.out.println("移动");
}
}
子类(蛇怪):
package mon;
public class Basilisk extends Monster{
public Basilisk(String mname,int hp,int atk){
this.mname=mname;
this.hp=hp;
this.atk=atk;
}
public void attack(){
System.out.println("怪物"+mname+"展开攻击\n当前生命值是:"+hp+"攻击力是:"+atk);
if(hp<10){
hp=hp+20;
System.out.println("实施大蛇补血术...当前生命值是"+hp);
}
}
public void move(){
System.out.println("我是"+super.mname+",我走S形路线");
}
}
子类(蜈蚣精):package mon;
public class Centipade extends Monster{
public Centipade(String mname,int hp,int atk){
this.mname=mname;
this.hp=hp;
this.atk=atk;
}
public void attack(){
System.out.println("怪物"+mname+"展开攻击\n当前生命值是:"+hp+"攻击力是:"+atk);
}
public void move(){
System.out.println("我是"+super.mname+",我在空中移动");
}
}
测试类:
package mon;
public class Test {
public static void main(String[] args) {
Basilisk b=new Basilisk("蛇怪", 5, 20);
b.attack();
b.move();
Centipade c=new Centipade("蜈蚣精", 60, 15);
c.attack();
c.move();
}
}
运行结果:
怪物蛇怪展开攻击
当前生命值是:5攻击力是:20
实施大蛇补血术...当前生命值是25
我是蛇怪,我走S形路线
怪物蜈蚣精展开攻击
当前生命值是:60攻击力是:15
我是蜈蚣精,我在空中移动