在两个构造函数中初始化最终变量
Initialize final variable in two constructors
我有两个变量。并且应该制作两个构造函数。
private int size;
final private Class clazz;
第一个:
public SomeConstr(int size) {
if (size <= 0) {
this.size = 0;
IllegalArgumentException argumentException = new IllegalArgumentException();
logger.log(Level.SEVERE, "", argumentException);
throw argumentException;
}
else
this.size = size;
this.clazz = Device.class;
}
}
第二个:
public ComeConstrSecond(int size, Class clazz) {
this(size);
if (clazz == null || !Device.class.isAssignableFrom(clazz)) {
logger.log(Level.SEVERE, "");
throw new IllegalArgumentException();
}
this.clazz = clazz;
}
当我在第二个构造函数中初始化 this.clazz = clazz
时,我遇到了类似 have been assigned to
的问题。如果我必须使用 this(size)
,如何正确写入 clazz
?
以相反的方式链接您的构造函数 - 从具有部分信息的构造函数到具有所有信息的构造函数:
public SomeConstr(int size) {
this(size, Device.class);
}
public SomeConstr(int size, Class clazz) {
if (size <= 0) {
IllegalArgumentException argumentException = new IllegalArgumentException();
logger.log(Level.SEVERE, "", argumentException);
throw argumentException;
}
if (clazz == null || !Device.class.isAssignableFrom(clazz)) {
logger.log(Level.SEVERE, "");
throw new IllegalArgumentException();
}
this.size = size;
this.clazz = clazz;
}
我有两个变量。并且应该制作两个构造函数。
private int size;
final private Class clazz;
第一个:
public SomeConstr(int size) {
if (size <= 0) {
this.size = 0;
IllegalArgumentException argumentException = new IllegalArgumentException();
logger.log(Level.SEVERE, "", argumentException);
throw argumentException;
}
else
this.size = size;
this.clazz = Device.class;
}
}
第二个:
public ComeConstrSecond(int size, Class clazz) {
this(size);
if (clazz == null || !Device.class.isAssignableFrom(clazz)) {
logger.log(Level.SEVERE, "");
throw new IllegalArgumentException();
}
this.clazz = clazz;
}
当我在第二个构造函数中初始化 this.clazz = clazz
时,我遇到了类似 have been assigned to
的问题。如果我必须使用 this(size)
,如何正确写入 clazz
?
以相反的方式链接您的构造函数 - 从具有部分信息的构造函数到具有所有信息的构造函数:
public SomeConstr(int size) {
this(size, Device.class);
}
public SomeConstr(int size, Class clazz) {
if (size <= 0) {
IllegalArgumentException argumentException = new IllegalArgumentException();
logger.log(Level.SEVERE, "", argumentException);
throw argumentException;
}
if (clazz == null || !Device.class.isAssignableFrom(clazz)) {
logger.log(Level.SEVERE, "");
throw new IllegalArgumentException();
}
this.size = size;
this.clazz = clazz;
}