Java

Java 19-5.1泛型

2019-01-15  本文已影响0人  第二套广播体操

泛型类
定义泛型类可以规定传入对象

public class Generic_Test3 {
    public static void main(String[] args) {
      util<MStudent> util= new util<MStudent>();
    util.setE(new MStudent("于松江",21));
        System.out.println(util.getE());
        System.out.println(util.getE().getName());
    }
}
class util<E>{
    private E e;

    public E getE() {
        return e;
    }

    public void setE(E e) {
        this.e = e;
    }
}

泛型类 和泛型方法

//在类上定义的泛型 不可以为静态 静态可以静态在方法上
public class Generic_Test4 {
    public static void main(String[] args) {
      Demo<Student> demo=new Demo<>();
      demo.Show(new Student());
      demo.print("Sting");

    }
}
class Demo<W>{//W是对象
    public void Show(W w){
    System.out.println(w);
    }
    public  static <Q> void print(Q s) {//泛型方法
        System.out.println(s);
    }

}

泛型接口

public class Generic_Test5 {
    public static void main(String[] args) {

    }
}
interface Inter<T>//接口自定义泛型 可以在类中实现自定义泛型
{
    public void show(T t);
}
class InterImpl implements Inter<String>{

    @Override
    public void show(String s) {

    }
}

如果实现类也无法确定泛型 可以在继承类中确定泛型:

public class Generic_Test5 {
    public static void main(String[] args) {
InterImpl1 interImpl1=new InterImpl1();
interImpl1.show("haha");
InterImpl<Integer> inter=new InterImpl<Integer>();
inter.show(2);
    }
}
interface Inter<T>//接口自定义泛型 可以在类中实现自定义泛型
{
    public void show(T t);
}
class InterImpl<Q> implements Inter<Q>{


    @Override
    public void show(Q q) {
        System.out.println(q);
    }
}
class InterImpl1 extends InterImpl<String>{
    @Override
    public void show(String s) {
        super.show(s);
    }
}
上一篇下一篇

猜你喜欢

热点阅读