public class GenericClass<T> {
private T value;
public GenericClass(T value) {
this.value = value;
}
public void printDoubleValue() {
if (value instanceof Integer) {
int intValue = (Integer) value;
System.out.println(intValue * 2);
} else {
System.out.println("Unsupported type for doubling.");
}
}
}
泛型类型参数在这个场景中的作用
- 增强代码复用性:通过使用泛型类型参数
T
,GenericClass
可以接受任意类型的数据作为成员变量 value
。这意味着我们不需要为不同类型单独编写不同的类,一个 GenericClass
就可以处理多种类型,提高了代码的复用性。
- 类型安全:在编译时,Java 编译器会检查泛型类型的使用是否正确。比如如果我们实例化
GenericClass
时传入了一个非 Integer
类型,编译器会报错,这样就避免了运行时类型错误,增强了程序的安全性。
- 灵活性:在使用
GenericClass
时,使用者可以根据具体需求指定 T
的实际类型,使得代码在保证类型安全的同时具有很高的灵活性。例如可以创建 GenericClass<Integer>
、GenericClass<String>
等不同类型的实例。