Definition of generic interface: the interface defined with generics becomes a generic interface
Interface message<t> { // generic interface publicString Echo (T msg); } |
In Java, there are two ways to implement a generic interface
1, continue to define generics on subclasses, and this generic type continues to be used on the interface
Interface message<t> { // generic interface publicString Echo (T msg); } class messageimpl<t> Implements message<t> { publicString Echo (T msg) { return"ECHO:"+ msg; } } public class testdemo { public static void main (string[] args) throws exception { message<string>msg = new messageimpl< String> (); System. out . println (Msg.echo (" Zhang San ")); } } |
2, set the specific type on the subclass
Interface message<t> { // generic interface publicString Echo (T msg); } class Messageimpl Implements message<string> { publicstring Echo (String msg) { return"ECHO:"+ msg; } } public class testdemo { public static void main (string[] args) throws exception { message<string>msg = new messageimpl (); System. out . println (Msg.echo (" Zhang San ")); } } |
Generic methods:
public class testdemo { publicstaticvoidmain (string[] args) throwsException { integerresult[] = get(1, 2, 3); for ( int temp:result) { // Even automatic unpacking contains System. out . println (temp); } } public static <T> t[] Get (T ... args ) { //T returnargs; } } |
This article from "inprovence" blog, declined reprint!
Generic interfaces and generic methods