How do I instantiate (inside a method) different classes that implement the same interface?

Just wondering if you can help me with my problem. This was probably due to the fact that I did not know the correct keywords to search for.

This is not homework, just anonymous ...

I have an interface and a bunch of implementing classes:

interface Fruit
Banana implements Fruit  
Apple implements Fruit  
....

      

I have a utility class Fruit. There is a method in this that takes any kind of Fruit and slices it up.

public static Fruit[] slice(Fruit f, int pieces)

      

How can I declare a Fruit array of the same type as the Fruit I that is passed to the method?

ie How can I automate:

Fruit[] a = new Apple[pieces];  

      

if i give him an apple?

...

edit: lightening

I will 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 a slice (Fruit f, int slice) or copy (Fruit f) so that I create the same Fruit type as in the arguments (without having to override the method for each type or do instance checks)

+2


source to share


2 answers


First, I suggest dropping reference arrays. Use instead List

. Then it's relatively simple:



public static <T extends Fruit> List<T> slice(T fruit, int pieces)

      

+6


source


Alternatively, you can use reflection: Array.newInstance (f.getClass (), pieces)



+1


source







All Articles