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?

2
  • 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. Commented Mar 12, 2019 at 20:23
  • 1
    Something like this: IntSorter[] sorters = new IntSorter[] { new Sorter1(), new Sorter2(), new Sorter3() new Sorter4() };. Commented Mar 12, 2019 at 20:24

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

Comments

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.