泛型

    xiaoxiao2021-12-14  21

    最近学了一点泛型的知识,下面是练习时写的代码

    public class Demo { public static void main(String[] args) { Father<String> f = new Father<String>("jack"); System.out.println(f.getT()); Father<Integer> f2 = new Father<Integer>(20); System.out.println(f2.getT()); } } class Father<T> { private T t; public Father() { } public Father(T t) { super(); this.t = t; } public T getT() { return t; } public void setT(T t) { this.t = t; } } 如果father有子类的话

    public class Demo7 { public static void main(String[] args) { Father<String> f = new Father<String>("jack"); System.out.println(f.getT()); Father<Integer> f2 = new Father<Integer>(20); System.out.println(f2.getT()); } } class Father<T> { private T t; public Father() { } public Father(T t) { super(); this.t = t; } public T getT() { return t; } public void setT(T t) { this.t = t; } } //子类指定了具体的类型 class Son extends Father<String>{ } //子类也需要使用泛型 class Son3<T> extends Father<T>{ } //错误写法,父类上定义有泛型需要进行处理 class Son2 extends Father<T>{ } 泛型接口

    public class Demo8 { public static void main(String[] args) { MyInter<String> my = new MyInter<String>(); my.print("泛型"); MyInter2 my2 = new MyInter2(); my.print("只能传字符串"); } } interface Inter<T> { void print(T t); } // 实现不知为何类型时可以这样定义 class MyInter<T> implements Inter<T> { public void print(T t) { System.out.println("myprint:" + t); } } //使用接口时明确具体类型。 class MyInter2 implements Inter<String> { @Override public void print(String t) { System.out.println("myprint:" + t); } }

    转载请注明原文地址: https://ju.6miu.com/read-968436.html

    最新回复(0)