Hey there,
I have stumbled upon this problem several times now without finding a satisfying solution:
There is a superclass
Fruit and a class
Banana which inherits from
Fruit.
Banana has the function
peel(), which the superclass
Fruit does not have.
I now have an
fruitArray:array<Fruit>,
from which I know that only bananas will be added to.When trying to call the
peel()-method on the array-members, the compiler will complain that fruits don't have the
peel()-method. And he is right doing so!
What I'm now trying to do is:
if (Type.getClass(fruitArray[i]) == Banana)
{
fruitArray[i].peel()
}
...but the compiler remains stubborn.
I know I could make the FruitArray a BananaArray or add the peel()-method to the Fruit-class, but that's not what I want.
I'm modifying structures of an existing framework, where limiting the capabilities of the FruitArray to a BananaArray is not an option, while cluttering the superclass with virtual functions seems terribly inefficient.
Is there a way to tell the compiler: "Hey, buddy, I know you're a little worried about the Fruit class not having the peel()-method, but relax - I can assure you that only peelable bananas will be on this party, although it is generally open to any kind of fruit."
Thanks in advance,
-sano98