最终未初始化字段的抽象类 [英] Abstract class with final uninitialized field
本文介绍了最终未初始化字段的抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道下面的代码是否有意义,因为编译器警告空白的最终字段对象可能尚未初始化。有没有更好的方法呢?
I was wondering if the below code makes any sense, since the compiler warns that "the blank final field objects may not have been initialized". Is there a better way of doing this?
public abstract Test {
protected final ArrayList<Object> objects;
}
public TestSubA extends Test {
public TestSubA() {
objects = new ArrayList<Objects>(20);
// Other stuff
}
}
public TestSubB extends Test {
public TestSubB() {
objects = new ArrayList<Objects>(100);
// Other stuff
}
}
推荐答案
我会将字段设为final并强制构造函数传递值:
I would make the field final and force the constructors to pass the value up:
public abstract class Test {
private final ArrayList<Object> objects;
protected ArrayList<Object> getObjects() {
return objects;
}
protected Test(ArrayList<Object> objects) {
this.objects = objects;
}
}
public class TestSubA extends Test {
public TestSubA() {
super(new ArrayList<Object>(20));
// Other stuff
}
}
public class TestSubB extends Test {
public TestSubB() {
super(new ArrayList<Object>(100));
// Other stuff
}
}
这篇关于最终未初始化字段的抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文