0

我有三个班级:

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;
    }


}

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

4

2 回答 2

1

您应该明确声明您正在对 的实例进行操作Unicycle,以便访问该addWheel()方法。您可以通过投射来做到这一点。

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

显然,如果您尝试对Unicycle不是 aUnicycle或其他子类的对象的实例进行强制转换,您将得到一个ClassCastException

于 2013-10-17T01:20:33.540 回答
1

bicycleArray被声明为一个数组,Bicycle并且它没有addWheel定义任何方法。

你正在尝试类似的东西:

Bicycle bicycle = new Bicycle();
bicycle = new Unicycle();
bicycle.addWheel(); // err
于 2013-10-17T01:21:18.410 回答