beginner_
beginner_

Reputation: 7632

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)

Upvotes: 3

Views: 382

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285460

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

Upvotes: 2

Kane
Kane

Reputation: 4167

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. `

Upvotes: 0

Related Questions