知识要点
1.泛型解析
泛型:顾名思义,指广泛的类型,即一种不确定的类型。可以在类中预支地使用未知的类型,即在创建对象时才确定要存储什么数据类型。当没有指定泛型时,默认类型为Object类型。
2.泛型类
定义:使用到泛型的类 定义格式:修饰符 class 类名<代表泛型的变量> { } 使用方式:先建立泛型类,在建立泛型对象时才确立泛型的类型 示例: 开发一个泛型Apple类,要求有一个重量属性weight在测试类中实例化不同的泛型对象,要求对象a1的这一属性是String类型,对象a2的这一属性是Integer型,a3的这一属性是Double型。分别为a1,a2,a3的重量属性赋值为:”500克”,500,500.0,在测试类中通过对象调用访问器得到属性值并输出。 步骤:
按照定义,建立Apple泛型类,并建立构造器,get()与set()方法:
package www. YZ. Test;
public class Apple < T> {
private T weight;
public Apple ( ) {
}
public Apple ( T weight) {
this . weight = weight;
}
public T getWeight ( ) {
return weight;
}
public void setWeight ( T weight) {
this . weight = weight;
}
@Override
public String toString ( ) {
return "Apple{" +
"weight=" + weight +
'}' ;
}
}
建立Test类,进行测试
package www. YZ. Test;
public class Test {
public static void main ( String[ ] args) {
Apple< String> apple1= new Apple < > ( "500克" ) ;
Apple< Integer> apple2= new Apple < > ( 500 ) ;
Apple< Double> apple3= new Apple < > ( 500.0 ) ;
System. out. println ( apple1. getWeight ( ) ) ;
System. out. println ( apple2. getWeight ( ) ) ;
System. out. println ( apple3. getWeight ( ) ) ;
}
}
输出结果 :