The following code is an example of java generics:
/**
* Class of custom property type
*
* @ Author limeteor
*
*/
Public class Student <T> {
String name; // name
T address; // address of the custom type
/**
* Get () method of the address
* @ Return custom type
*/
Public T getAddress (){
Return address;
}
/**
* Set () method of the address
* @ Param custom type
*/
Public void setAddress (T address ){
This. address = address;
}
/**
* Get () method of name
* @ Return String type
*/
Public String getName (){
Return name;
}
/**
* Set () method of name
* @ Param name
*/
Public void setName (String name ){
This. name = name;
}
/**
* Construction method without Parameters
*/
Public Student (){
Super ();
}
/**
* There are two parameter constructor methods.
* @ Param name
* @ Param address
*/
Public Student (String name, T address ){
Super ();
This. name = name;
This. address = address;
}
/**
* Main () method
* @ Param args
*/
Public static void main (String [] args ){
Student <String> stu = new Student <String> ();
Stu. name = "Limeteor ";
Stu. address = "No. 158, Xi'an, Shaanxi, China ";
System. out. println (stu. getAddress ());
Student <Address> stu1 = new Student <Address> ();
Stu1.setName ("qingqing ");
Stu1.setAddress (new Address ("China", "Shaanxi", "Xian", 158 ));
System. out. println (stu1.getAddress ());
}
}
/**
* Define a class
*
* @ Author limeteor
*
*/
Class Address {
String country; // country
String city; // city
String street; // street
Int no; // house number
/**
* Construction Method with Parameters
*
* @ Param country
* @ Param city
* @ Param street
* @ Param no
*/
Public Address (String country, String city, String street, int no ){
Super ();
This. country = country;
This. city = city;
This. street = street;
This. no = no;
}
/**
* Method without Parameters
* @ Return returns the detailed address information.
*/
Public String toString (){
Return country + city + street + no + "no ";
}
}
Important knowledge points are:
1. Defining a generic class is to define a name in the angle brackets after the class name, representing a data type, which is used in this class.
2. T can be called a specific data type in a program.
3. T can be used as the member variable type, method parameter type, and method return value type in the class.
4. When defining the Student object, you must specify the actual type of T. Here, the String type is specified, and the Address type is also specified.