package cooom;
/**
* 自定义泛型类
* @author 冀帅
* @date 2020/8/13-22:26
*/
public class Order <T> {
String orderName;
int orderId;
//类的内部结构就可以使用类的泛型
T orderT;//定义一个不知道什么类型的变量orderT
public Order(){};
public Order(String orderName,int orderId,T orderT){
this.orderId = orderId;
this.orderName = orderName;
this.orderT = orderT;
}
public T getOrderT(){
return orderT;
}
public void setOrderT(T orderT){
this.orderT = orderT;
}
@Override
public String toString() {
return "Order{" +
"orderName='" + orderName + '\'' +
", orderId=" + orderId +
", orderT=" + orderT +
'}';
}
}
package cooom;
/**
* @author 冀帅
* @date 2020/8/13-22:51
*/
public class SubOrder extends Order<Integer>{//SubOrder不再是泛型类
}
package cooom;
/**
* @author 冀帅
* @date 2020/8/13-22:55
*/
public class SubOrder1<T> extends Order<T>{//SubOrder1<T>仍然为泛型类
}
package cooom;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.junit.Test;
/** 自定义泛型结构:泛型类丶泛型接口;泛型方法 。
*
* 1.关于自定义反省类,泛型接口:
*
*
*
* @author 冀帅
* @date 2020/8/13-22:41
*/
public class GenericTest1 {
@Test
public void test1(){
//如果定义了泛型类,实例化时没有指明类的泛型,则认为此泛型类型为Object类型
//要求:如果定义了类带泛型的,建议在实例化时要指明泛型的类型
Order order = new Order();
order.setOrderT(123);
order.setOrderT("ABC");
//建议:实例化时指明类的泛型
Order<String> order1 = new Order<String>("orderAA",1001,"order:AA");
order1.setOrderT("AA:hello");
}
@Test
public void test2(){
SubOrder sub1 = new SubOrder();//在定义SubOrder类时已经指定过泛型类型,不用在这里在指定了
//由于子类在继承带泛型的父类时,指明了泛型类型,则实例化子类对象时,不用再指明泛型类型。
sub1.setOrderT(1122);
SubOrder1<String> sub2 = new SubOrder1<>();
sub2.setOrderT("order2...");
}
}