【发布时间】:2020-05-13 17:27:43
【问题描述】:
我有两个类,一个是泛型类,另一个是泛型的子类。我不确定如何为每个类创建构造函数。下面是代码示例:
public class A<T> {
protected T personInfo;
protected int age;
protected String firstName;
protected String lastName;
protected int id;
protected Long port;
protected String ipAddress;
public A(T personInfo, int age, String firstName, String lastName, int id, Long port, String
ipAddress) {
this.personInfo = personInfo;
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.port = port;
this.ipAddress = ipAddress;
}
}
public class B extends A<maleInfo> {
protected maleInfo personInfo; //not sure if this is necessary
public B(//do I need this?)
...
}
基本上,所有变量都被 B 使用,B 使用maleInfo 作为泛型 T。如果我在泛型类中创建构造函数,intelliJ 会说 B 类中的“personInfo”可能未初始化。实现这一目标的正确方法是什么?
另外,如果我在基类中为 personInfo(通用)创建 getter/setter,子类是否还需要为其创建 getter/setter?
【问题讨论】:
标签: java generics constructor