s-day02--泛型方法的使用
This commit is contained in:
@@ -0,0 +1,16 @@
|
|||||||
|
package com.inmind.generic_method03;
|
||||||
|
|
||||||
|
public class Demo06 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//问一下手机修理师傅,您修得挺好,会不会修平板?
|
||||||
|
Phone phone = new Phone();
|
||||||
|
Pad pad = new Pad();
|
||||||
|
Factory<Phone> phoneFactory = new Factory<>();
|
||||||
|
System.out.println("平板坏了");
|
||||||
|
Pad fixedPad = phoneFactory.fixAll(pad);
|
||||||
|
fixedPad.study();
|
||||||
|
String s = "我是来凑数";
|
||||||
|
String fixS = phoneFactory.fixAll(s);
|
||||||
|
System.out.println(fixS);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.inmind.generic_method03;
|
||||||
|
|
||||||
|
public class Pad {
|
||||||
|
|
||||||
|
public void study(){
|
||||||
|
System.out.println("使用平板来学习");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "小米平板";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.inmind.generic_method03;
|
||||||
|
|
||||||
|
public class Phone {
|
||||||
|
|
||||||
|
public void playApp(){
|
||||||
|
System.out.println("手机在玩应用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "苹果手机";
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user