从另一个类调用子类方法时出错

时间:2013-10-17 01:18:17

标签: java inheritance polymorphism

我有三个班级:

public class BikeSystem {

    static Bicycle[] bicycleArray = new Bicycle[100];
    static int currentBikes = 0;

    public static void addUnicycle() {

        bicycleArray[currentBikes] = new Unicycle();
        currentBikes++; 
    }

    public static void addUniWheel() {
        for (int i=0; i < currentBikes; i++) {
            if (bicycleArray[i] instanceof Unicycle)
                bicycleArray[i].addWheel();
        }
     }
}

public class Bicycle {

    // some variables

}

public class Unicycle extends Bicycle {

    private int wheels;

    public boolean addWheel() {
        wheels++;
        return true;
    }


}

但是,当我尝试在BikeSystem类中调用bicycleArray[i].addWheel()方法时,我一直收到“找不到符号”错误。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您应该明确声明您正在使用Unicycle的实例进行操作才能访问addWheel()方法。你可以通过施放来做到这一点。

((Unicycle) bicycleArray[i]).addWheel();

显然,如果您尝试在不是Unicycle或更远的子类的对象的实例上转换为Unicycle,您将获得ClassCastException

答案 1 :(得分:1)

bicycleArray被声明为Bicycle的数组,并且没有定义addWheel方法。

你正在尝试类似的东西:

Bicycle bicycle = new Bicycle();
bicycle = new Unicycle();
bicycle.addWheel(); // err