自定义泛型类

package demo02;

/**
 * @description: demo05
 * @author: liuyang
 * @create: 2021-09-04 17:18
 */
public class Demo05 {
    public static void main(String[] args) {
        Order<Integer> order = new Order<>("AAAA", "aaaa", 100);
        Integer orderType = order.getOrderType();
        System.out.println(orderType);

        SubOrder1 subOrder1 = new SubOrder1();
        subOrder1.setOrderType(120);
        System.out.println(subOrder1.getOrderType());

        SubOrder2<String> subOrder2 = new SubOrder2();
        subOrder2.setOrderType("100");
        System.out.println(subOrder2.getOrderType());
    }
}

/**
 * 自定义泛型类,泛型类型是在实例化对象的时候确定的
 * @param <T>
 */
class Order<T> {
    private String orderId;
    private String orderName;
    private T orderType;

    public Order() {

    }

    public Order(String orderId, String orderName, T orderType) {
        this.orderId = orderId;
        this.orderName = orderName;
        this.orderType = orderType;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public String getOrderName() {
        return orderName;
    }

    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }

    public T getOrderType() {
        return orderType;
    }

    public void setOrderType(T orderType) {
        this.orderType = orderType;
    }
}

/**
 * 此时SubOrder1并不是一个泛型类
 */
class SubOrder1 extends Order<Integer> {
}

/**
 * 此时SubOrder2继承了父类的泛型类型
 * @param <T>
 */
class SubOrder2<T> extends Order<T> {

}

 

自定义泛型类

上一篇:面向对象程序设计 Object Oriented Design


下一篇:非技术探讨:文章定时发布功能如何实现