简体   繁体   English

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

[英]Error calling a subclass method from another class

I have three classes: 我有三个班:

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


}

However, I keep getting a "cannot find symbol" error when I try to call the bicycleArray[i].addWheel() method in my BikeSystem class. 但是,当我尝试在BikeSystem类中调用bicycleArray[i].addWheel()方法时,我一直收到“无法找到符号”错误。 How do I get around this? 我该如何解决这个问题?

You should explicitly state that you are operating on an instance of Unicycle in order to gain access to the addWheel() method. 你应该明确地指出你在实例操作Unicycle ,以获得对addWheel()方法。 You can do this by casting. 你可以通过施法来做到这一点。

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

Obviously, if you try to cast to Unicycle on an instance of an object that is not a Unicycle or a further subclass, you will get a ClassCastException 显然,如果你尝试转换为Unicycle上的对象不是一个实例Unicycle或进一步的子类,你会得到一个ClassCastException

bicycleArray is declared as an array of Bicycle and there is no addWheel method defined by it. bicycleArray被声明为Bicycle数组,并且没有定义addWheel方法。

You're trying something similar as: 你正在尝试类似的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM