0

I have 4 classes, all implementing an interface IntSorter. All classes have a sort method, so for each class I want to call sort on an array.

I thought something like this would work:

IntSorter[] classes = new IntSorter[] {
Class1.class, Class2.class, Class3.class, Class4.class
};
for (Class c : classes)
    c.sort(array.clone());

But classes cannot hold the .class names, I get the error Type mismatch: cannot convert from Class<Class1> to IntSorter

So I tried

Class[] classes = new Class[] {
Class1.class, Class2.class, Class3.class, Class4.class
};
for (Class c : classes)
    c.sort(array.clone());

But now c.sort() cannot be called. I tried parsing the class to an IntSorter first, with (IntSorter) c but then I get the error Cannot cast from Class to IntSorter

How do I fix this?

da1g
  • 107
  • 2
  • 7
  • If IntSorter is an interface, an array IntSorter[] must be initialized with objects which implement IntSorter. The first example is closer to what you want. But, instead of putting the several class objects into IntSorter[], put instances of these classes. – Thomas Bitonti Mar 12 '19 at 20:23
  • 1
    Something like this: IntSorter[] sorters = new IntSorter[] { new Sorter1(), new Sorter2(), new Sorter3() new Sorter4() };. – Thomas Bitonti Mar 12 '19 at 20:24

2 Answers2

2

Use the first approach, but you want for (IntSorter c : classes) - and you need to put instances in your array (not the classes). Something like,

IntSorter[] classes = new IntSorter[] {
    new Class1(), new Class2(), new Class3(), new Class4()
};
for (IntSorter c : classes) {
    c.sort(array.clone());
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

You are attempting to create array of classes instead of array of instances of classes implementing IntSorter.

Check this question to understand difference between Classes, Objects and Instances: The difference between Classes, Objects, and Instances

Your code should look something like this, as far as I can tell with limited information available:

IntSorter[] classes = new IntSorter[] {
new Class1(), new Class2(), new Class3(), new Class4()
};
for (IntSorter c : classes)
    c.sort(array.clone());
uaraven
  • 1,097
  • 10
  • 16