One: Wildcard characters
Because generics are initialized to determine the type of data, and the method that accepts this property of this object or object is fixed, it is necessary to judge and limit the types of these properties that pass through this method, otherwise, a method that can only come out of an integer type if passed in a string type, An error occurs during the execution of this method. If this method can handle any type of data, you can use the wildcard character ". "To receive.
Example 1:
Package haizhu.com;
Class student<t>{
private T name;
Public T GetName () {
return name;
}
public void SetName (T name) {
this.name = name;
}
}
public class GenericDemo01 {public
static void function (Student<?> s) { //use ". "indicates that this method can receive a property of T corresponding to any data type
System.out.println (" name is: "+s.getname ());
}
public static void Main (string[] args) {
student<string> s = new student<string> ();
S.setname ("Haizhu");
function (s);
}
}
II: Generic Upper and lower limits
However, in general, some methods can only handle a subset of data types, this time you can use the upper and lower limits to determine the range, the format is as follows:
Generic limit:
<? Extends Class >
Example 2:
public static void function (STUDENT<? extends number> s) {
System.out.println ("name is:" +s.getname ());
}
Indicates that only the data type of the class of number and the subclass of this class can be received. (Extends table inheritance, that's what's underneath this class)
Generic Lower limit:
<? Super Class >
Example 3:
public static void function (STUDENT<? super Number> s) {
System.out.println ("name is:" +s.getname ());
}
Indicates that only the class of number and the data type of the parent class of this class can be received. (Super Table parent class, more than this class of things)