s-day02-泛型方法的使用

This commit is contained in:
2026-07-31 10:53:15 +08:00
parent af6120ea2f
commit e6ac76cd25
8 changed files with 73 additions and 10 deletions
@@ -1,4 +1,4 @@
package com.inmind.generic04; package com.inmind.generic_class05;
public class Demo08 { public class Demo08 {
public static void main(String[] args) { public static void main(String[] args) {
@@ -1,4 +1,4 @@
package com.inmind.generic04; package com.inmind.generic_class05;
/* /*
能不能在一个类中定义一个未知类型,接收的具体的是什么类型,就返回什么类型这个数据类型要动态 能不能在一个类中定义一个未知类型,接收的具体的是什么类型,就返回什么类型这个数据类型要动态
并省略掉强转操作也避免类型转换异常 并省略掉强转操作也避免类型转换异常
@@ -11,18 +11,18 @@ package com.inmind.generic04;
*/ */
public class Factory<T> { public class Factory<T> {
//多态的写法
/*public Object fixObj(Object o) {
System.out.println("对象已修好");
return o;
}*/
//使用T类型 //使用T类型
public T fix(T t) { public T fix(T t) {
System.out.println("对象T已修好"); System.out.println("对象T已修好");
return t; return t;
} }
//多态的写法
/*public Object fixObj(Object o) {
System.out.println("对象已修好");
return o;
}*/
/*//维修手机方法 /*//维修手机方法
public Phone fixPhone(Phone phone) { public Phone fixPhone(Phone phone) {
System.out.println("手机修好了"); System.out.println("手机修好了");
@@ -1,4 +1,4 @@
package com.inmind.generic04; package com.inmind.generic_class05;
public class Pad { public class Pad {
public void playApp(){ public void playApp(){
@@ -1,4 +1,4 @@
package com.inmind.generic04; package com.inmind.generic_class05;
public class Phone { public class Phone {
@@ -0,0 +1,21 @@
package com.inmind.generic_method06;
public class Demo09 {
public static void main(String[] args) {
//手机工厂
Factory<Phone> phoneFactory = new Factory<>();
Phone phone = new Phone();
Phone fixedPhone = phoneFactory.fix(phone);
/*
得到 二维码小卡片,发现这个师傅修得很好,这个师傅说其实我很多都能修,不仅是手机
*/
Pad pad = new Pad();
Pad fixedPad = phoneFactory.fixAll(pad);
Phone fixedPhone1 = phoneFactory.fixAll(phone);
fixedPad.playApp();
fixedPhone1.call();
}
}
@@ -0,0 +1,27 @@
package com.inmind.generic_method06;
public class Factory<T> {
//使用T类型(这只是一个使用了泛型类中的T类型的普通方法)
public T fix(T t) {
System.out.println("对象T已修好");
return t;
}
/*
需求:我们希望在一个工厂类中接私活,定义出一个功能,接收任意类型的数据,动态返回该类型的数据,可以实现吗??
可以,只能通过泛型方法
泛型方法格式:表示在一个方法中定义一个未知的类型
方法修饰符 <任意大写字母>返回值类型 方法名(参数列表){
方法体;
}
泛型方法的泛型类型何时确定???
当方法被调用时才确定,一般泛型方法中字母尽量不要与泛型类的字母一致
*/
public <E> E fixAll(E e) {
System.out.println("来什么,我就修理什么!!!666");
return e;
}
}
@@ -0,0 +1,7 @@
package com.inmind.generic_method06;
public class Pad {
public void playApp(){
System.out.println("看抖音");
}
}
@@ -0,0 +1,8 @@
package com.inmind.generic_method06;
public class Phone {
public void call() {
System.out.println("打电话");
}
}