异常与接口
以下例子中重点掌握内容
1、接口与子类的合理运用
(1)接口可在类存在某种功能时使用,提供单个或多个接口;
(2)子类继承在子父类存在继承关系,如子类需运用后面父类方法等时使用。
2、接口内方法不可具象化,需在类实现时重写接口中方法;
3、类在强制转换过程中,如果是转换为接口,接口与类不需存在继承关系,可以直接强转;
4、数组等易出现异常的位置使用异常上抛,上抛时可设置异常信息,并在main方法中try catch处理;
5、自定义异常如下,设置无参及有参的异常构造方法,后面catch时通过.message()方法给出异常信息。
public class WeaponException extends Exception{
public WeaponException(){
}
public WeaponException(String s){
super(s);
}
}`
package ExceptionPractice;
public class Army {
//定义武器数组
private Weapon[] weapons;
//构造方法,设定Army初始化数量
public Army(int count){
weapons = new Weapon[count];
}
//增加武器方法
public void addWeapon(Weapon weapon) throws WeaponException{
for (int i = 0;i<weapons.length;i++){
if(null == weapons[i]){ //如武器数组非空即可继续添加武器
weapons[i] = weapon;
System.out.println(weapon+"武器添加成功");
return;
}
}
throw new WeaponException("武器已达上限"); //如以上代码不再执行即for循环结束,则异常抛出
}
public void attackAll(){ //可攻击的武器攻击
for (int i = 0;i<weapons.length;i++){ //遍历武器数组 查找可攻击武器
if (weapons[i] instanceof Attack){ //instance of不仅可判断对象是否属于类 也可判断是否实现接口
Attack attacks = (Attack) weapons[i]; //判定weapon实现Attack后 (相当于Attack是weapon[i]接口的子类,把接口当做父类理解)进行向下转型,接口即为抽象类
attacks.attack();
}
}
}
public void moveAll(){
for (int i = 0;i<weapons.length;i++){
if (weapons[i] instanceof Move){
Move move = (Move) weapons[i];
move.move();
}
}
}
}
package ExceptionPractice;
/*
* 定义Weapon类*/
public class Weapon {
}
package ExceptionPractice;
/*
* 设定weapon所需要的功能move*/
public interface Move {
//注意接口的方法不能有实体
public void move();
}
package ExceptionPractice;
/*
* 设定weapon所需要的功能attack*/
public interface Attack {
//注意接口的方法不能有实体
public void attack();
}
package ExceptionPractice;
public class Tank extends Weapon implements Attack,Move {
@Override
/*
重写attack方法*/
public void attack() {
System.out.println("坦克攻击");
}
/*
重写move方法*/
@Override
public void move() {
System.out.println("坦克移动");
}
}
package ExceptionPractice;
/*设置weapon子类*/
public class Rocket extends Weapon implements Attack {
@Override/*
重写attack方法*/
public void attack() {
System.out.println("火箭发射");
}
}
package ExceptionPractice;
public class Plane extends Weapon implements Move,Attack {
@Override
//重写attack
public void attack() {
System.out.println("飞机攻击");
}
@Override
//重写move方法
public void move() {
System.out.println("飞机移动");
}
}
package ExceptionPractice;
public class Thingplane extends Weapon implements Move{
@Override
//重写attack方法
public void move() {
System.out.println("运输机移动");
}
}
package ExceptionPractice;
public class WeaponException extends Exception{
public WeaponException(){
}
public WeaponException(String s){
super(s);
}
}
package ExceptionPractice;
public class Test {
public static void main(String[] args) {
Army army = new Army(5);
Rocket r = new Rocket();
Plane p = new Plane();
Tank n = new Tank();
Thingplane t = new Thingplane();
try
{
army.addWeapon(r);
army.addWeapon(p);
army.addWeapon(n);
army.addWeapon(t);
}
catch(WeaponException e){
System.out.println(e.getMessage());
}
army.moveAll();
army.attackAll();
}
}