This question already has answers here:
Calling a subclass method from superclass
                                
                                    (4个答案)
                                
                        
                                3年前关闭。
            
                    
我想让一个对象处理多个扩展对象。最终结果应该是我通过自行车或摩托车,它将显示信息。在下面的示例中,我希望一个类(显示)接受Bike或MotorBike(扩展了Bike)并适当显示信息。故障点在Display(显示器)中,最后一行显示MotorBike独有的信息。我确定我缺少一些简单的东西,但是我只是不明白我在做错什么。

谢谢你的帮助。

问题.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
        }
    }
}

最佳答案

在生产线上

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


您正在从成员'bike'访问方法'getEngineCC',但是'bike'是Bike类型,而不是MotorBike,因此,如果仅使用'bike'则无法获取方法'getEngineCC'。尝试类型转换:

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

10-08 19:11