Write a Objecttool class
Generic method: Defines a generic type on a method
Format public < generic type > return type method name (generic type)
The benefits are:
This generic method can receive any type of data
1 Public class Objecttool {2publicvoid show (T t) {3System.out.println (t ); 4 }5 }
Write a test class again
1 public class Objecttooldemo { public static void main (string[] args) { 3 objecttool ot = Objecttool (); 4 ot.show ("Hello" ); 5 ot.show (100 6 ot.show (true 7 8 }
Write a generic interface class first
Generic interface: Defines generics on an interface
1 Public Interface Inter<t> {2publicabstractvoid show (T t); 3 }
Implementation class:
1 /* 2 Implementing a class when implementing an interface3 The first case: you already know what the type is.4 */5 //Public class Interimpl implements inter<string> {6 //7 //@Override8 //Public void Show (String t) {9 //System.out.println (t);Ten // } One // } A - //The second case: I don't know what type it is. - Public classInterimpl<t>ImplementsInter<t> { the - @Override - Public voidShow (T t) { - System.out.println (t); + } - } + A /*
Test class
1 Public classInterdemo {2 Public Static voidMain (string[] args) {3 //test of the first case4 //inter<string> i = new Interimpl ();5 //i.show ("Hello");6 7 // //test of the second case8inter<string> i =NewInterimpl<string>();9I.show ("Hello");Ten OneInter<integer> II =NewInterimpl<integer>(); AIi.show (100); - } -}
Java 16-7 generic method and generic interface (generic class similar)