The definition of generics, compared to the normal class definition, first adds a type variable identified by the angle brackets after the class name, typically denoted by T. T can be used anywhere in a generic type. This is also true for generalization interfaces.
Let's take a look at the generic type of box and box's code:
(1) Definition of ordinary box
public class mybox{
Private Object object;
public void Add (Object object) {
This.object = object;
}
public object Get () {
return object;
}
}
(2) Generic definition of box class
public class mybox<t>{
Private T T;
public void Add (T t) {
THIS.T = t;
}
Public T get () {
return t;
}
}
In the generic definition of the Mybox class, the "public class Mybox" in the class declaration is changed to "public class mybox<t>", and all objects in the Mybox class body are replaced with T, which defines mybox as an abstract type that can hold various types of object containers of a certain type .
Package practice;
public class Myboxtest {
public static void Main (string[] args) {
TODO auto-generated Method Stub
mybox<string> Abox = new mybox<string> ();
Abox.add (New String ("GA Suen"));
String i = Abox.get ();
System.out.println (i);
}
}
Output:
ga Suen
public class Myboxtest {
public static void Main (string[] args) {
TODO auto-generated Method Stub
mybox<integer> Abox = new mybox<integer> ();
Abox.add (Newinteger ("2018"));
Integer i = Abox.get ();
System.out.println (i);
}
}
Output:
2018
Definitions of Java generic classes