简体   繁体   中英

interface implementations with different concrete types as method parameters

I would like to have a method in an interface that accepts any Type of a generic object, like

public void myMethod(List<?>);

Now the implementations should only accept a certain type, eg. implementations 1:

public void myMethod(List<Integer>);

Implementation 2:

public void myMethod(List<String>);

However this does not work as public void myMethod(List<Integer>); is not a valid implementaion of public void myMethod(List<?>);

How could I achieve this? (Besides using an Object Parameter and hence rely on casting and do type checking manually)

Unless I'm missing something obvious (which happens too much for my liking), why not make the interface itself generic?

public interface MyInterface<T> {
   public void myMethod(List<T> list);
}

Which can be implemented like so:

public class MyClass<T> implements MyInterface<T> {

   @Override
   public void myMethod(List<T> list) {
      // TODO complete this!      
   }

}

and used like so:

public class Foo {
   public static void main(String[] args) {
      MyClass<String> myString = new MyClass<String>();
      MyClass<Integer> myInt = new MyClass<Integer>();
   }
}

You may want to you types: http://docs.oracle.com/javase/tutorial/java/generics/gentypes.html

for example, use public void myMethod(List<T>);

for your interface, and then your concrete classes are instatiated with the type you want. `

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM