s-day02--泛型类的使用

This commit is contained in:
xx
2026-10-13 15:14:56 +08:00
parent 10d159a451
commit b82dafad8a
4 changed files with 66 additions and 0 deletions
@@ -0,0 +1,19 @@
package com.inmind.generic02;
public class Demo05 {
public static void main(String[] args) {
//买了平板与手机,质保,找专门的厂家去修理
Pad pad = new Pad();
System.out.println("平板坏了");
Factory<Pad> padFactory = new Factory<>();
Pad fixedPad = padFactory.fix(pad);
fixedPad.study();
Phone phone = new Phone();
System.out.println("手机坏了");
Factory<Phone> phoneFactory = new Factory<>();
Phone fixedPhone = phoneFactory.fix(phone);
fixedPhone.playApp();
}
}
@@ -0,0 +1,21 @@
package com.inmind.generic02;
/*
能不能在一个类中定义一个未知的类型,接收的具体是什么类型,就返回该类型,这个数据类型要动态,并省略掉强转操作,避免了
类型转换异常???
可以,使用泛型类,在类名后加上<大写字母>
泛型类的格式:
public class 类名<大写字母>
泛型类的T类型,何时确定的呢???
创建对象时确定该类型
*/
public class Factory <T>{
//修理T类型的设备即可
public T fix(T t) {
System.out.println("工厂修理了设备"+t);
return t;
}
}
+13
View File
@@ -0,0 +1,13 @@
package com.inmind.generic02;
public class Pad {
public void study(){
System.out.println("使用平板来学习");
}
@Override
public String toString() {
return "小米平板";
}
}
@@ -0,0 +1,13 @@
package com.inmind.generic02;
public class Phone {
public void playApp(){
System.out.println("手机在玩应用");
}
@Override
public String toString() {
return "苹果手机";
}
}