在Java中,泛型类的定义是通过在类名后面添加尖括号(< >)来指定类型参数的。要检查泛型类的定义,可以按照以下步骤进行:
public class MyGenericClass<T> {
private T data;
public MyGenericClass(T data) {
this.data = data;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
MyGenericClass<String> stringInstance = new MyGenericClass<>("Hello, World!");
MyGenericClass<Integer> integerInstance = new MyGenericClass<>(123);
System.out.println(stringInstance.getData()); // 输出 "Hello, World!"
System.out.println(integerInstance.getData()); // 输出 123
public class MySubGenericClass<T> extends MyGenericClass<T> {
public MySubGenericClass(T data) {
super(data);
}
}
MyGenericClass<?> genericInstance = new MyGenericClass<>("Wildcard");
public class MyMultiGenericClass<K, V> {
private K key;
private V value;
public MyMultiGenericClass(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}
public class MyRestrictedGenericClass<T extends Number> {
private T data;
public MyRestrictedGenericClass(T data) {
this.data = data;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
通过以上步骤,可以检查和使用泛型类的定义。
领取专属 10元无门槛券
手把手带您无忧上云