2021.03.04
第25次记录
跟着做的,自己还是做不出来
需求:
写一个类Army,代表一支军队,这个类有一个属性Weapon数组weapons(用来存储该军队所拥有的所有武器)
该类还提供一个构造方法,在构造方法里通过传一个int类型的参数来限定该类所能拥有的最大武器数量,
初始化数组weapons。
该类还提供一个方法addWeapon(Weapon wa),表示把参数wa所代表的武器加入到数组w中。
在这个类中还定义两个方法attackAll()让w数组中的所有武器攻击,以及moveAll(),让w数组中的所有
可移动的武器移动。
写一个主方法测试以上程序。
提示:Weapon是一个父类,有很多子武器。这些子武器有一些是可移动的,有一些是可攻击的。
代码演示:
定义可移动的接口
public interface Moveable {
void move();
}
定义可射击的接口
public interface Shootable {
void shoot();
}
定义武器类
public class Weapon {
}
定义武器坦克类
public class Tank extends Weapon implements Moveable, Shootable {
public void move() {
System.out.println("坦克移动");
}
public void shoot() {
System.out.println("坦克开炮");
}
}
定义武器高射炮类
public class GaoShePao extends Weapon implements Shootable {
public void shoot(){
System.out.println("高射炮轰击");
}
}
定义武器战斗机类
public class Fighter extends Weapon implements Moveable, Shootable {
public void move(){
System.out.println("战斗机起飞");
}
public void shoot(){
System.out.println("战斗机射击");
}
}
定义运输机类
public class WuZiFeiJi extends Weapon implements Moveable{
public void move(){
System.out.println("运输机运送物资");
}
}
定义军队类
public class Army {
private Weapon[] weapons;
public Weapon[] getWeapons() {
return weapons;
}
public void setWeapons(Weapon[] weapons) {
this.weapons = weapons;
}
public Army(){
}
public Army(int count){
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();
}
}
}
}
自定义异常类
public class AddWeaponException extends Exception{
public AddWeaponException(){
}
public AddWeaponException(String s){
super(s);
}
}
定义测试类
public class ArmyTest {
public static void main(String[] args) {
Army army = new Army(4);
Tank tank = new Tank();
GaoShePao gaoshepao = new GaoShePao();
Fighter fighter = new Fighter();
WuZiFeiJi wz = new WuZiFeiJi();
try {
army.addWeapon(tank);
army.addWeapon(gaoshepao);
army.addWeapon(fighter);
army.addWeapon(wz);
}catch (AddWeaponException e){
System.out.println(e.getMessage());
}
army.moveAll();
army.attackAll();
}
}
输出结果:
javaseAdvance.Tank@74a14482:武器添加成功
javaseAdvance.GaoShePao@1540e19d:武器添加成功
javaseAdvance.Fighter@677327b6:武器添加成功
javaseAdvance.WuZiFeiJi@14ae5a5:武器添加成功
坦克移动
战斗机起飞
运输机运送物资
坦克开炮
高射炮轰击
战斗机射击