Java——关于异常、接口、集合的练习【战争】
作者:互联网
题目要求:
开放性题目,随意发挥;
建立一个武器集合,包括添加武器,遍历武器使得各武器能充分发挥功能,其中功能包括可移动、可攻击。最好不要面向具体编程,降低程序的耦合度,提高扩展力,再添加过程中若出现武器满的情况在控制台作出反馈,但不停止程序
测试类
package zhandou; import java.util.ArrayList; import java.util.List; public class text{ public static void main(String[] args) { List<Weapon> weaponList = new ArrayList<>(); Weapon GaoShePao = new GaoShePao("C"); Weapon TanKe = new TanKe("A"); Weapon YunShuJi = new YunShuJi("B"); Weapon ZhanDouJi = new ZhanDouJi("D"); weaponList.add(GaoShePao); weaponList.add(TanKe); weaponList.add(YunShuJi); weaponList.add(ZhanDouJi); try { if (weaponList.size() > 4) throw new WeaponException("越界"); } catch (WeaponException e) { System.out.println(e.getMessage()); } for(Weapon data:weaponList){ if (data instanceof Moveable) { Moveable m = (Moveable) data; m.move(); System.out.println("$$$$$$$$$$$"); }if (data instanceof Shootable) { Shootable b = (Shootable) data; b.shoot(); System.out.println("############"); } } } }
武器越界异常
package zhandou; public class WeaponException extends Exception{ public WeaponException() { } public WeaponException(String message) { super(message); } }
移动接口
package zhandou; public interface Moveable { void move(); }
射击接口
package zhandou; public interface Shootable { void shoot(); }
父类:武器
package zhandou; public class Weapon { }
子类: 战斗机
package zhandou; public class ZhanDouJi extends Weapon implements Shootable,Moveable{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public ZhanDouJi(String name) { this.name = name; } public ZhanDouJi() { } public void shoot() { System.out.println("战斗机射击!"); } public void move(){ System.out.println("战斗机起飞!"); } }
子类:高射炮
package zhandou; public class GaoShePao extends Weapon implements Shootable{ private String name; public GaoShePao(String name) { this.name = name; } public GaoShePao() { } public void setName(String name) { this.name = name; } public String getName() { return name; } public void shoot() { System.out.println("高射炮射击!"); } }
子类:坦克
package zhandou; public class TanKe extends Weapon implements Moveable,Shootable{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public TanKe() { } public TanKe(String name) { this.name = name; } public void move() { System.out.println("坦克启动!"); } public void shoot(){ System.out.println("坦克射击!"); } }
子类:运输机
package zhandou; public class YunShuJi extends Weapon implements Moveable{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public YunShuJi() { } public YunShuJi(String name) { this.name = name; } public void move() { System.out.println("运输机起飞!"); } }
题后总结 :
1)抛出异常方面代码思路不够明确,其中若自定义集合中的异常,不知道如何写,只能出现自抛自抓的情况
2)父类型能转型称为接口类型,没有想到真的能实现,是在测试中发现的;
3)以后写程序要把接口、类、放在不同的Java class/interface,思路更加清晰
标签:Java,String,void,练习,接口,println,Weapon,public,name 来源: https://blog.csdn.net/m0_61163395/article/details/122628120