day15--ooday09(多态、submarine项目:水雷入场、深水炸弹与潜艇的碰撞、得分、增加命数)
1.多态
-
-
同一类型的引用指向不同的对象时,有不同的实现---所有抽象方法都是多态的
-----行为的多态
-
同一个对象被造型为不同类型时,有不同的功能---所有对象都是多态的
-----对象的多态
-
-
向上造型/自动类型转换
-
超类型的引用指向派生类的对象
-
能点出什么,看引用类型
-
能造型成为的数据类型:超类+所实现的接口
-
-
强制类型转换,成功的条件只有如下两种
-
引用所指向的对象,就是该类型
-
引用所指向的对象,实现了该接口或者继承了该类
-
-
强转时若不符合上述条件,则发生ClassCastException类型转换异常;因此强转前先通过instanceof判断引用的对象是否是该类型
public class MultiTypeDemo {
public static void main(String[] args) {
Aoo o = new Boo(); //向上造型
Boo o1 = (Boo)o; //引用o指向的对象就是Boo
Inter o2 = (Inter)o; //引用o指向的对象实现了Inter接口
//Coo o3 = (Coo)o; //运行时发生ClassCastException类型转换异常
if(o instanceof Coo){ //false
Coo o4 = (Coo)o;
}else{
System.out.println("o不是Coo类型");
}
}
}
interface Inter{
}
class Aoo{
}
class Boo extends Aoo implements Inter{
}
class Coo extends Aoo{
}
2.submarine项目
-
水雷入场--后半段
-
水雷是由水雷潜艇发射出来的,所以在MineSubmarine中设计shootMine()生成水雷对象
-
水雷入场为定时发生的,所以在run中调用MineEnterAction()实现水雷入场 在MineEnterAction()中: 每1000毫秒,遍历所有潜艇,判断若是水雷潜艇则强转为水雷潜艇类型, 获取水雷对象obj,mines扩容,将obj添加到末尾
-
-
深水炸弹与潜艇的碰撞
-
在SeaObject中设计isHit()检测碰撞、goDead()去死
在Battleship中设计addLife()增命
-
深水炸弹与潜艇的碰撞为定时发生的,所以在run中调用bombBangAction()实现炸弹与潜艇碰撞在bombBangAction()中:
-
代码
class SeaObject{
/** 检测碰撞 */
public boolean isHit(SeaObject other){
this:一个对象
other:另一个对象
}
假设: s表示潜艇,b表示深水炸弹,m表示水雷,ship表示战舰
1) s.isHit(b); //this指潜艇,other指深水炸弹
2) b.isHit(s); //this指深水炸弹,other指潜艇
3) m.isHit(ship); //this指水雷,other指战舰
4) ship.isHit(m); //this指战舰,other指水雷
}
int score = 0; //玩家得分
public void bombBangAction(){ //每10毫秒走一次
for(int i=0;i<bombs.length;i++){ //遍历所有炸弹
Bomb b = bombs[i]; //获取每个炸弹
for(int j=0;j<submarines.length;j++){ //遍历所有潜艇
SeaObject s = submarines[j]; //获取每个潜艇
if(b.isLive() && s.isLive() && s.isHit(b)){ //若都活着,并且还撞上了
s.goDead(); //潜艇去死
b.goDead(); //炸弹去死
if(s instanceof EnemyScore){
EnemyScore es = (EnemyScore)s;
score += es.getScore();
}
if(s instanceof EnemyLife){
EnemyLife el = (EnemyLife)s;
int num = el.getLife();
ship.addLife(num);
}
//----------复用性差、扩展性差、维护性差-----------垃圾代码
if(s instanceof ObserveSubmarine){
ObserverSubmarine os = (ObserveSubmarine)s;
score += os.getScore();
}
if(s instanceof TorpedoSubmarine){
TorpedoSubmarine ts = (TorpedoSubmarine)s;
score += ts.getScore();
}
if(s instanceof MineSubmarine){
MineSubmarine ms = (MineSubmarine)s;
int num = ms.getLife();
ship.addLife(num);
}
if(s instanceof NuclearSubmarine){
NuclearSubmarine ns = (NuclearSubmarine)s;
score += ns.getScore();
int
-