s-day02--泛型方法的使用
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
package com.inmind.generic_method03;
|
||||
/*
|
||||
需求:我们希望在一个工厂类中接私活,定义出一个功能,接收任意类型的数据,动态返回该类型的数据,可以实现吗??
|
||||
可以,只能通过泛型方法
|
||||
|
||||
泛型方法格式:表示在一个方法中定义了一个未知的类型
|
||||
|
||||
方法修饰符 <大写字母> 返回值类型 方法名(参数列表){
|
||||
方法体
|
||||
}
|
||||
|
||||
泛型方法的泛型类型何时确定呢??
|
||||
方法调用时才确定
|
||||
|
||||
注意:
|
||||
1.泛型在类中和方法中可以定义多个
|
||||
2.泛型类和泛型方法是可以分开定义
|
||||
*/
|
||||
public class Factory <T>{
|
||||
|
||||
//修理T类型的设备即可
|
||||
public T fix(T t) {
|
||||
System.out.println("工厂修理了设备"+t);
|
||||
return t;
|
||||
}
|
||||
|
||||
//定义一个方法,这个方法能够修理任意类型(手机,平板,耳机)
|
||||
public <A> A fixAll(A a) {//泛型方法
|
||||
System.out.println("师傅接了私活,修理了:"+a);
|
||||
return a;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user