java:集合框架(泛型方法的概述和使用)

xiaoxiao2021-07-05  192

* A:泛型方法概述     * 把泛型定义在方法上 * B:定义格式         * public <泛型类型> 返回类型 方法名(泛型类型 变量名) * C:案例演示     * 泛型方法的使用

声明泛型方法:

public class Tool<Q> { private Q q; public Q getObj() { return q; } public void setObj(Q q) { this.q = q; } public void show(Q q) {//方法泛型最好要与类的泛型一致 System.out.println(q); } public<T> void show1(T t) {//如果不一致,需要在方法上声明自己的泛型,方法拥有自己的泛型 System.out.println(t); } public static<W> void show2(W w) {//静态方法随着类的加载而加载,必须声明自己的泛型,因为在静态方法加载的时候,还可能没有创建对象 System.out.println(w); } }

调用泛型方法:

import com.heima.bean.Student; import com.heima.bean.Tool; import com.heima.bean.worker; public class Demo3_Generic { public static void main(String[] args) { Tool<String> t=new Tool<>(); t.show("abc"); } }

 

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

最新回复(0)