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. 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. 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
bicycleArray
is declared as an array of Bicycle
and there is no addWheel
method defined by it.
You're trying something similar as:
Bicycle bicycle = new Bicycle();
bicycle = new Unicycle();
bicycle.addWheel(); // err
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.