Hi all
Just wondering if you're able to help me with my problem. This has probably come about by my not knowing the right keywords to search for.
This is not homework, just anonymised...
I have an interface and a bunch of implementing classes:
interface Fruit
Banana implements Fruit
Apple implements Fruit
....
I have a Fruit utilities class. In this is a method that takes any sort Fruit and slices it.
public static Fruit[] slice(Fruit f, int pieces)
How can I declare the Fruit array to be of the same type as the Fruit I pass to the method?
ie How can I automate:
Fruit[] a = new Apple[pieces];
if I give it an Apple?
.
edit:clarification
I'll have code like this:
Fruit a = new Apple();
Fruit b = new Banana();
Fruit[] slices1 = FruitUtil.slice(a, 3); //slices1 should be an Apple
Fruit[] slices2 = FruitUtil.slice(b, 3); //slices2 should be a Banana
Fruit newApple = FruitUtil.copy(a); //newApple should be an Apple
How do I write slice(Fruit f, int slice) or copy(Fruit f) method such that I create the same type of Fruit as what I passed in the arguments (without having to override the method for each type, or doing instanceof checks)