Say I have a generic array like this:
ArrayList<Fruit> fruits = new ArrayList<Fruit>();
Then I add lots of different fruits, which all extends the class fruit, and loop through them
for (Fruit f : fruits) {
}
If the fruit is a banana, I want to check how round it is, so..
for (Fruit f : fruits) {
if (f instanceof Bannana)
f.checkHowRoundBannanaIs();
}
I will have to put the checkHowRoundBannnaIs() method in the fruit class, even though the fruit may not be a banana, because I can’t use the function on f if it isn’t in the fruit class, otherwise I get a undefined method error (or something like that).
This is fine for one or two methods, but after a while it makes the class bulky and ugly. So my question is, how can I add methods to a class and use them in a for-style loop of its super class?
Short answer, you can’t really.
If you want to call the methods in the body of the for-loop,
instanceofand down-casting is the only way I can think of:Both
instanceofand down-casting are usually considered bad practice though. To avoid it, you could implement the visitor pattern. Here are the steps you would need to take:Create a visitor interface like this:
Let all fruits accept a visitor:
Create a visitor that takes the appropriate action for each type of fruit, and pass it as argument to the
acceptmethod of each fruit in your list: