泛型类 泛型方法 以及泛型接口 and 泛型的继承和通配符

文章详细介绍了Java中的泛型概念,包括泛型类如Box的使用,泛型方法如printArray的声明,以及泛型接口如List的定义。此外,还探讨了泛型在继承中的应用,如BoxUtil中使用?extendsWeightable的通配符来限制参数类型,以及BoxWithWeight如何继承并扩展功能,实现获取权重的方法。
摘要由CSDN通过智能技术生成

泛型类 

前面已经讲过泛型的作用 就如同看门老大爷一样.

下面是基础代码

public class Box<T> {
    private T data;
    public void setData(T data) {
        this.data = data;
    }
    public T getData() {
        return data;
    }
}

在此处<T>如同泛类是对输入类型的限制 

其中 private T data中的T如同int 是类型的定义

泛型 方法

public static <T> void printArray(T[] array) {
    for (T element : array) {
        System.out.println(element);
    }
}

与泛型类大同小异. 前面学懂自然明白.

泛型接口

interface List<T> {
    void add(T element);
    T get(int index);
}

与前面一样 T指定返回类型

继承与通配符

public class Box<T> {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

public class BoxUtil {
    public static double getWeight(Box<? extends Weightable> box) {//如果?super表示所有父类
        return box.get().getWeight();
    }
}

public interface Weightable {
    double getWeight();
}

public class Apple implements Weightable {
    private double weight;

    public Apple(double weight) {
        this.weight = weight;
    }

    public double getWeight() {
        return weight;
    }
}

public static void main(String[] args) {
    Box<Apple> box = new Box<>();
    Apple apple = new Apple(0.5);
    box.set(apple);
    double weight = BoxUtil.getWeight(box);
    System.out.println("Weight: " + weight);
}
public class Box<T> {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

public class BoxWithWeight<T extends Weightable> extends Box<T> {
    public double getWeight() {
        return get().getWeight();
    }
}

public interface Weightable {
    double getWeight();
}

public class Apple implements Weightable {
    private double weight;

    public Apple(double weight) {
        this.weight = weight;
    }

    public double getWeight() {
        return weight;
    }
}

public static void main(String[] args) {
    BoxWithWeight<Apple> box = new BoxWithWeight<>();
    Apple apple = new Apple(0.5);
    box.set(apple);
    double weight = box.getWeight();
    System.out.println("Weight: " + weight);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值