JAVA——泛型类和泛型方法(静态方法泛型)
来源:互联网 发布:通过js给html元素赋值 编辑:程序博客网 时间:2024/05/16 08:57
泛型类定义的泛型,在整个类中有效。如果被方法是用,那么
泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了。
为了让不同的方法可以操作不同类型,而且类型还不确定。那么
可以将泛型定义在方法上。
泛型类
class Demo<T>{ public void show(T t) { System.out.println("show: "+t); } public void print(T t) { System.out.println("show: "+t); }}
class GenericDemo4{ public static void main(String[] args) { Demo<Integer>d = new Demo<Integer>(); d.show(new Integer(4)); Demo<String>d1 = new Demo<String>(); d1.print("haha"); }}
结果:
show: 4
show: haha
泛型方法
class Demo{ public <T> void show(T t) { System.out.println("show: "+t); } public <Q> void print(Q q) { System.out.println("print:"+q); }}
class GenericDemo4{ public static void main(String[] args) { Demo d = new Demo(); d.show("hello boy!"); d.print("Alex i love you !"); }}
结果:
show: hello boy!
print:Alex i love you !
同时定义泛型类和泛型方法
class Demo<T>{ public void show(T t) { System.out.println("show: "+t); } public <Q> void print(Q q) { System.out.println("print:"+q); }}class GenericDemo4{ public static void main(String[] args) { Demo <String> d = new Demo<String>(); d.show("hello boy!"); d.print("Alex i love you !"); d.print(5); d.print("heiei"); }}
结果:
show: hello boy!
print:Alex i love you !
print:5
print:heiei
特殊之处:
静态方法不可以访问类上定义的泛型
如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。
class Demo<T>{ public void show(T t) { System.out.println("show: "+t); } public <Q> void print(Q q) { System.out.println("print:"+q); } public static <W>void method(W t) { System.out.println("method: "+t); }}class GenericDemo4{ public static void main(String[] args) { Demo <String> d = new Demo<String>(); d.show("hello boy!"); d.print("Alex i love you !"); d.print(5); d.print("heiei"); Demo.method("hihi"); }}
结果:
show: hello boy!
print:Alex i love you !
print:5
print:heiei
method: hihi
泛型定义在接口上
interface Inter<T>{ void show(T t);}//第一种class InterImpl implements Inter<String>{ public void show(String t) { System.out.println("show :"+t); }}/*第二种class InterImpl<T>implements Inter<T>{ public void show(T t) { System.out.println("show :"+t); }}*/class GenericDemo5{ public static void main(String[] args) { /* InterImpl<Integer> i = new InterImpl<Integer>(); i.show(4); */ InterImpl i = new InterImpl(); i.show("haha"); }}
结果:
show :haha
第一种相对来说就比较死,固定为String类型了。而第二种可以自己定义。
1 0
- JAVA——泛型类和泛型方法(静态方法泛型)
- JAVA 泛型方法 和 静态方法泛型
- JAVA 泛型方法 和 静态方法泛型
- JAVA 泛型方法 和 静态方法泛型
- Java静态泛型方法
- java学习——静态方法和非静态方法
- Java泛型静态方法调用问题
- java 之 静态泛型方法
- 静态泛型方法
- Java(静态方法和实例方法)
- java静态方法,静态初始化块及静态变量的声明和初始化不能使用泛型的原因
- Java泛型在静态方法中的使用
- Java基础----Java---集合框架---泛型、泛型方法、静态方法泛型、泛型接口、泛型限定、泛型类
- JAVA泛型类和泛型方法
- Java自定义泛型类和泛型方法
- java中的泛型类和泛型方法
- Java ——静态变量、常量和方法
- java 静态方法和静态变量 static
- 【HTML】3.Form表单
- HDU 1166 敌兵布阵
- Java 设计模式(十二) 依赖倒置原则(DIP)
- 新手编译开发OpenWrt入门教程(自定义固件、ubuntu学习)
- Gedit相关配置
- JAVA——泛型类和泛型方法(静态方法泛型)
- HDU 1850-Being a Good Boy in Spring Festival(Nim博弈)
- TCP/IP模型的各层的作用
- 空心等腰三角形的打印
- iOS开发的几个小问题(一)
- 冒泡排序算法(排序详解)
- MyBatis 二级缓存原理
- 游戏生涯感想开端(一)
- nyoj 123 士兵杀敌(四)