关于Java泛型的若干问题

时间:2023-02-26 11:31:11

在实例化对象时不指定泛型,则自动识别为object。

<span style="font-size:18px;">/**
*
*在定义类时,定义泛型
*/

public class People <T>{
private T name;
private T age;

public People(){

}
public T getName() {
return name;
}
public void setName(T name) {
this.name = name;
}
public T getAge() {
return age;
}
public void setAge(T age) {
this.age = age;
}

}</span>

调用

<span style="font-size:18px;">/**
* 在实例化对象时不指定泛型,则自动识别为object
*
*
*/

public class FanXing2 {

public static void main(String[] args) {
// 如果实例化对象时,不指定泛型,则认为是Object
People people = new People();
// 里面的参数是Object类型
people.setName("刘备");
people.setAge("12");

String ageString= (String) people.getAge();
String nameString=(String) people.getName();

System.out.println(nameString);
System.out.println(ageString);


}

}
</span>

在继承泛型类的时候,子类没有声明泛型参数,编译器不会发出任何警告,入下代码中

class Derived2 extends GenericBase {} // No warning

不会有警告,只有在调用方法中需要用到泛型参数的时候才会有警告如下代码有警告

d2.set(obj); // Warning here!

继承声明时,中父类的泛型参数不能用?代替,否则编译不通过;
如下代码


class Derived3 extends GenericBase<?> {}
// Strange error:
// unexpected type found : ?
// required: class or interface without bounds

以下是Java编程思想376开始的代码

class GenericBase<T> {
private T element;
public void set(T arg) { arg = element; }
public T get() { return element; }
}

class Derived1<T> extends GenericBase<T> {}

class Derived2 extends GenericBase {} // No warning

// class Derived3 extends GenericBase<?> {}
// Strange error:
// unexpected type found : ?
// required: class or interface without bounds

public class ErasureAndInheritance {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Derived2 d2 = new Derived2();
Object obj = d2.get();
d2.set(obj); // Warning here!
}
} ///:~