7

Simple design and simple code but don't compile:

public interface Insertable {
    public String getInsertStmt(String table);
}

public class ClassCanBeInserted implements Insertable { 
    public String getInsertStmt(String table) {}
}

public class SomeClass { 
    public static void main() { 
        List<ClassCanBeInserted> list = new ArrayList<ClassCanBeInserted>();
        SomeMethod(list);
    }
    private static void SomeMethod(List<Insertable> list) {}
}

And the call to SomeMethod() won't compile. English poor but the code should explain. Can someone please figure out what's wrong and how to get a design for the propose that a list of interface-implemented classes can be used in such method?

Again, English poor, so may not expressed well. Let me know your questions. Thanks!

Error message given: The method SomeMethod(List) in the type ClassCanBeInserted is not applicable for the arguments (List)

jmj
  • 237,923
  • 42
  • 401
  • 438
X.M.
  • 941
  • 3
  • 14
  • 22

2 Answers2

17

List<Insertable> is not a superclass of List<ClassCanBeInserted>, even though Insertable is a superclass of ClassCanBeInserted. To do what you want, you should change the SomeMethod signature to SomeMethod(List<? extends Insertable> list).

Jordi
  • 5,846
  • 10
  • 40
  • 41
  • Thanks, this helped me solve my problem. In addition, if in your function you want to declare an object of the generic type, you can declare your function with `public static void SomeMethod(List list) {}`. You can then declare a variable of that type with `T varName;` – Kevin Lawrence Jul 09 '15 at 18:28
1

This does seem counter intuitive at first.

I guess the reason is that the whole point of generics is to introduce and constrain the list based on static type safety.

If you could put any 'Insertable' into the list then you could end up with a mixture of different class types conotained in there.

This means that your gets become unsafe and are at risk of ClassCastExceptions.

Benjamin Wootton
  • 2,089
  • 20
  • 21