This is better than you code for the interface. For instance:
In myMethod:
<T extends <? super Item>> void (T item);
This tells the compiler that it accepts only the generic type T, which is an implementation / extension of the Item interface / class. This will make sure that this input matches the correct type. The compiler guarantees this.
In the main class:
Item myItem = new SpecificItem();
The code above is best practice. Get used to it. But (I am discouraging this) you can also code this:
SpecificItem myItem = new SpecificItem();
You can read the Java source code. For example, in the java.util.Collections class. In the sort (List) method, you can notice that Joshua Bloch is sure that this input is always in the correct format. To try, do the following:
public class Class1 { public static void main(String[] args) { List<Class1> list = new ArrayList<Class1>(); Collections.sort(list); } }
Above code will create a compilation error. To fix this compilation error, Class1 must implement the Comparable interface. This supports the List sorting prerequisite, which assumes that this input is a list of comparisons.
Oh, I almost forgot about your question. This is actually not bad code, as it works. I just want to tell you that there is a better way to do this.
source share