package MyProject;
//所有武器的父类
public class Weapon {
}
Shootable类(接口)
package MyProject;
public interface Shootable {
//射击行为
void shoot();
}
Moveable类(接口)
package MyProject;
public interface Moveable {
//移动方法
void move();
}
Tank类
package MyProject;
//坦克是一种武器,可移动,可攻击
public class Tank extends Weapon implements Moveable,Shootable{
@Override
public void move() {
System.out.println("坦克移动");
}
@Override
public void shoot() {
System.out.println("坦克开炮");
}
}
Fighter类
package MyProject;
//战斗机是一种武器,可移动,可射击
public class Fighter extends Weapon implements Moveable,Shootable{
@Override
public void move() {
System.out.println("战斗机起飞");
}
@Override
public void shoot() {
System.out.println("战斗机开跑!");
}
}
GaoShePao类
package MyProject;
//高射炮是一种武器,可射击,不可移动
public class GaoShePao extends Weapon implements Shootable{
@Override
public void shoot() {
System.out.println("高射炮开炮!!!");
}
}
WuZiFeiJi类
package MyProject;
//物资飞机
public class WuZiFeiJi extends Weapon implements Moveable{
@Override
public void move() {
System.out.println("运输机起飞!");
}
}
Army类
package MyProject;
public class Army {
//武器数组
private Weapon[] weapons;
//创建军队的构造方法
public Army(int count){
//动态初始化数组中每一个元素默认值是null
//武器组组没有放武器
weapons = new Weapon[count];
}
//将武器加入数组
public void addWeapon(Weapon weapon) throws AddWeaponException{
for (int i = 0; i < weapons.length; i++) {
if(null == weapons[i]){
weapons[i] = weapon;
System.out.println(weapon+":武器添加成功!");
return;
}
}//程序如果执行到这,说明武器没有添加成功
throw new AddWeaponException("武器数量已经达到上限!");
}
//所有可攻击的武器
public void attackAll(){
//遍历数组
for (int i = 0; i < weapons.length; i++) {
if(weapons[i] instanceof Shootable){
//调用子类中特有的方法,向下转型
Shootable shootable = (Shootable)weapons[i];
shootable.shoot();
}
}
}
//所有课移动的武器
public void moveAll(){
//遍历数组
for (int i = 0; i < weapons.length; i++) {
if(weapons[i] instanceof Moveable){
//调用子类中特有的方法,向下转型
Moveable moveable = (Moveable)weapons[i];
moveable.move();
}
}
}
}
AddWeaponException类(异常类)
package MyProject;
//添加武器异常
public class AddWeaponException extends Exception{
public AddWeaponException(){
}
public AddWeaponException(String s){
super(s);
}
}
Test类
package MyProject;
public class Test {
public static void main(String[] args) {
//构建一个军队
Army army = new Army(4);//军队只有四个武器
//创建武器
Fighter fighter = new Fighter();
Fighter fighter2 = new Fighter();
GaoShePao gaoShePao = new GaoShePao();
Tank tank = new Tank();
WuZiFeiJi wuZiFeiJi = new WuZiFeiJi();
//添加武器
try {
army.addWeapon(fighter);
army.addWeapon(gaoShePao);
army.addWeapon(tank);
army.addWeapon(wuZiFeiJi);
army.addWeapon(fighter2);
} catch (AddWeaponException e) {
System.out.println(e.getMessage());
/* MyProject.Fighter@27973e9b:武器添加成功!
MyProject.GaoShePao@312b1dae:武器添加成功!
MyProject.Tank@7530d0a:武器添加成功!
MyProject.WuZiFeiJi@27bc2616:武器添加成功!
武器数量已经达到上限!*/
}
//所有可移动的移动
army.moveAll();//战斗机起飞 坦克移动 运输机起飞!
//所有可攻击的攻击
army.attackAll();//战斗机开跑 高射炮开炮!!! 坦克开炮
}
}