2016-05-10 69 views
1

我想有一個對象處理多個擴展對象。最終的結果應該是我通過一輛自行車或摩托車它會顯示信息。在我的例子中,我想讓一個類(Display)接受Bike或MotorBike(它擴展了Bike)並適當地顯示信息。失敗點在Display中,最後一行打印MotorBike所特有的信息。我確信我錯過了一些簡單的東西,但我只是不明白我做錯了什麼。一個對象使用相同的代碼處理多個擴展對象

感謝您的幫助。

Problem.java

public class Problem { 
    public static void main(String[] args) { 
     new Display(new Bike()); 
     new Display(new MotorBike()); 
    } 
} 

Bike.java

class Bike { 
    private boolean frontTireOk; 
    private boolean backTireOk; 
    private int gears; 

    public Bike() {} 

    public boolean isFrontTireOk() { 
     return frontTireOk; 
    } 

    public void setFrontTireOk(boolean frontTireOk) { 
     this.frontTireOk = frontTireOk; 
    } 

    public boolean isBackTireOk() { 
     return backTireOk; 
    } 

    public void setBackTireOk(boolean backTireOk) { 
     this.backTireOk = backTireOk; 
    } 

    public int getGears() { 
     return gears; 
    } 

    public void setGears(int gears) { 
     this.gears = gears; 
    } 
} 

摩托車,JAVA

class MotorBike extends Bike { 

    private int engineCC; 

    public MotorBike() {} 

    public int getEngineCC() { 
     return engineCC; 
    } 

    public void setEngineCC(int engineCC) { 
     this.engineCC = engineCC; 
    } 
} 

Display.java

class Display { 

    Bike bike; 

    public Display(Bike bike) { 
     this.bike = (Bike) bike; 
     showBike(); 
    } 

    Display(MotorBike motorBike) { 
     this.bike = (MotorBike) motorBike; 
     showBike(); 
    } 

    private void showBike() { 

     System.out.println("Front tire is OK ?" + bike.isFrontTireOk()); 
     System.out.println("Back tire is OK? " + bike.isBackTireOk()); 
     System.out.println("Gears? " + bike.getGears()); 

     if(bike instanceof MotorBike){ 
      System.out.println("Engine CC? " + bike.getEngineCC()); <--FAIL 
     } 
    } 
} 

回答

0

在線路

System.out.println("Engine CC? " + bike.getEngineCC()); 

你從構件「自行車」訪問方法「getEngineCC」,而是「自行車」是式自行車,摩托車沒有的,因此該方法「getEngineCC」不能被獲取如果你只是單獨使用「自行車」。嘗試類型化:

System.out.println("Engine CC? " + ((MotorBike)bike).getEngineCC()); 
+0

謝謝!我知道這很簡單。那麼,如果你知道的話很簡單。 :) – Techogre