泛型(java)
下面代码是java泛型的例子
/**
* 自定义属性类型的类
*
* @author limeteor
*
*/
public class Student<T> {
String name;//名称
T address;//自定义类型 的地址
/**
* 地址的get()方法
* @return 自定义类型
*/
public T getAddress(){
return address;
}
/**
* 地址的set()方法
* @param 自定义类型
*/
public void setAddress(T address){
this.address = address;
}
/**
* 名称的get()方法
* @return String类型
*/
public String getName(){
return name;
}
/**
* 名称的set()方法
* @param name
*/
public void setName(String name){
this.name = name;
}
/**
* 无参数的构造方法
*/
public Student(){
super();
}
/**
* 有二个参数的构造方法
* @param name
* @param address
*/
public Student(String name,T address){
super();
this.name = name;
this.address = address;
}
/**
* main()方法
* @param args
*/
public static void main(String[] args) {
Student<String> stu = new Student<String>();
stu.name="Limeteor";
stu.address = "中国陕西西安158号";
System.out.println(stu.getAddress());
Student<Address> stu1 = new Student<Address>();
stu1.setName("qingqing");
stu1.setAddress(new Address("中国", "陕西", "西安", 158));
System.out.println(stu1.getAddress());
}
}
/**
* 定义一个类
*
* @author limeteor
*
*/
class Address {
String country;// 国家
String city;// 城市
String street;// 街道
int no;// 门牌号
/**
* 带参数的构造方法
*
* @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;
}
/**
* 无参数的方法
* @return 返回详细的地址信息
*/
public String toString() {
return country + city + street + no + "号";
}
}
要注意的知识点有
1.定义一个泛型类,就是在类名后面的尖括号中定义一个名称,代表一个数据类型,在本类中被用到。
2.T在程序中可以称为一种特定的数据类型。
3.T在类中可以用作成员变量的类型,方法参数类型,方法返回值类型。
4.在定义Student对象时,需要指明T的实际类型,这里指定的是String类型,同样指明的是Address类型。

浙公网安备 33010602011771号