怎么做正规网站,网站建设对用户影响,微信_网站提成方案点做,注册域名后怎么做网站java 泛型的上限与下限 设置泛型对象的上限使用extends,表示参数类型只能是该类型或该类型的子类#xff1a;
声明对象#xff1a;类名? extends 类 对象名
定义类#xff1a;类名泛型标签 extends 类{}
设置泛型对象的下限使用super,表示参数类型只能是…java 泛型的上限与下限 设置泛型对象的上限使用extends,表示参数类型只能是该类型或该类型的子类
声明对象类名? extends 类 对象名
定义类类名泛型标签 extends 类{}
设置泛型对象的下限使用super,表示参数类型只能是该类型或该类型的父类
声明对象类名? super 类 对象名称
定义类类名泛型标签 extends类{}
public static void show(List? extends Number l){}
public static void show(List? super String l){}
泛型的上限
public static void main(String[] args) {PersonInteger p1 new Person();p1.setVal(99);PersonDouble p2 new Person();p2.setVal(3.14);PersonString p3 new Person();p3.setVal(007);show(p1);//√show(p2);//√show(p3);//×
}public static void show(Person? extends Number p){//此处限定了Person的参数类型只能是Number或者是其子类而String并不属于Number。System.out.println(p.getVal());}泛型的下限 public static void main(String[] args) {PersonInteger p1 new Person();p1.setVal(99);//IntegerPersonDouble p2 new Person();p2.setVal(3.14);//DoublePersonString p3 new Person();p3.setVal(007);//StringPersonObject p4 new Person();p4.setVal(new Object());//Objectshow(p1);//×show(p2);//×show(p3);//√show(p4);//√}public static void show(Person? super String p){System.out.println(p.getVal());}很好的例子
package generic;
import java.util.ArrayList;
import java.util.List; public class GenericDemo3 {public static void main(String[] args) {//因为show方法是用List?通配符接收的所以可以是任意类型ListString l1 new ArrayList();//new ArrayListString()show(l1);ListDouble l2 new ArrayList();show(l2);ListNumber l3 new ArrayList();show(l3); ListObject l4 new ArrayList();show(l4);//使用up方法的话接收类型为Number或者其子类//up(l1);//错误因为up方法接收类型为Number或者其子类l1String不符合up(l2);up(l3);//使用down方法的话接收类型为Number或者其父类//down(l2);errordown(l3);down(l4);}public static void down(List? super Number l){for (Object object : l) {System.out.println(object);}}public static void up(List? extends Number l){for (Object object : l) {System.out.println(object);}}public static void show(List? l){for (Object object : l) {System.out.println(object);}}}