NolanPower NolanPower - 8 months ago 32
Java Question

Java: Calling an interface's function from a Generic List that Extends it

I want to have a list of objects that all inherit from the same interface that contains the function go().

public interface goers{
public void go();

Now I have 3 classes that all implement go, for the sake of simplicity let's just call them A, B, and C.

In another class I have a
List<Class<? extends goers>>
that I want to do.

for (Class<? extends goers> gos : list)

But it won't compile because the compiler doesn't pick up the go method from the interface being applied to all of the members of the list.


A List<Class<? extends goers>> doesn't have a goers instance that you can call .go() on. You just have classes, not any instances of that classes. There's nothing to call .go() on.

You could try instantiating those classes, or having a List<goers> in the first place, which lets you call it how interfaces are intended to be used.