Java------泛型

    技术2022-07-14  60

    例:泛型类 class GeneralType <Type>{ Type object; public GeneralType(Type object){ this.object=object; } public Type getObj(){ return object; } } public class Text { public static void main(String[] args) { GeneralType<Integer> i=new GeneralType<Integer>(2); GeneralType<Double> d=new GeneralType<Double>(0.33); System.out.println("i.object="+(Integer)i.getObj()); System.out.println("i.object="+(Double)d.getObj()); //System.out.println("i.object="+(Integer)d.getObj()); //编译错误 } } 例:泛型方法 class GeneralMethod{ <Type> void printClassName(Type object){ System.out.println(object.getClass().getName()); } } public class Text { public static void main(String[] args) { GeneralMethod gm=new GeneralMethod(); gm.printClassName("Hello"); gm.printClassName(3); gm.printClassName(3.0f); gm.printClassName(3.0); } } //运行结果 //java.lang.String //java.lang.Integer //java.lang.Float //java.lang.Double 例:使用通配符 class GeneralType <Type>{ Type object; public GeneralType(Type object){ this.object=object; } public Type getObj(){ return object; } } class ShowType{ public void show(GeneralType<?> o){ System.out.println(o.getObj().getClass().getName()); } } public class Text { public static void main(String[] args) { ShowType st=new ShowType(); GeneralType<Integer> i=new GeneralType<Integer>(2); GeneralType<String> s=new GeneralType<String>("Hello"); st.show(i); st.show(s); } } //运行结果: //java.lang.Integer //java.lang.String 有限制的泛型 在参数"Type"后面使用"extends"关键字并加上类名或接口名,表明参数所代表的类型必须是该子类或者实现了该接口 注意,对于实现了某接口的有限制泛型,也是使用extends关键字。而不是implements关键字 class GeneralType<Type extends Number>{ Type object; public GeneralType(Type object){ this.object=object; } public Type getObj(){ return object; } } public class Text { public static void main(String[] args) { GeneralType<Integer> i=new GeneralType<Integer>(2); } }
    Processed: 0.010, SQL: 9