[英]Initializing final fields in Java
我有一個包含許多最終成員的類,可以使用兩個構造函數之一進行實例化。 構造函數共享一些代碼,這些代碼存儲在第三個構造函數中。
// SubTypeOne and SubTypeTwo both extend SuperType
public class MyClass {
private final SomeType one;
private final SuperType two;
private MyClass(SomeType commonArg) {
one = commonArg;
}
public MyClass(SomeType commonArg, int intIn) {
this(commonArg);
two = new SubTypeOne(intIn);
}
public MyClass(SomeType commonArg, String stringIn) {
this(commonArg);
two = new SubTypeTwo(stringIn);
}
問題是這段代碼沒有編譯: Variable 'two' might not have been initialized.
有人可能會從MyClass中調用第一個構造函數,然后新對象將沒有“兩個”字段集。
那么在這種情況下,在構造函數之間共享代碼的首選方法是什么? 通常我會使用輔助方法,但共享代碼必須能夠設置最終變量,這只能從構造函數中完成。
這個怎么樣? (更新了已更改的問題)
public class MyClass {
private final SomeType one;
private final SuperType two;
public MyClass (SomeType commonArg, int intIn) {
this(commonArg, new SubTypeOne(intIn));
}
public MyClass (SomeType commonArg, String stringIn) {
this(commonArg, new SubTypeTwo(stringIn));
}
private MyClass (SomeType commonArg, SuperType twoIn) {
one = commonArg;
two = twoIn;
}
}
您需要確保在每個構造函數中初始化所有最終變量。 我要做的是有一個構造函數初始化所有變量,並讓所有其他構造函數調用,傳入null
或一些默認值,如果有一個字段,他們沒有給出值。
例:
public class MyClass {
private final SomeType one;
private final SuperType two;
//constructor that initializes all variables
public MyClas(SomeType _one, SuperType _two) {
one = _one;
two = _two;
}
private MyClass(SomeType _one) {
this(_one, null);
}
public MyClass(SomeType _one, SubTypeOne _two) {
this(_one, _two);
}
public MyClass(SomeType _one, SubTypeTwo _two) {
this(_one, _two);
}
}
您需要做的就是確保初始化“兩個”。 在第一個構造函數中,只需添加:
two = null;
除非在只調用第一個構造函數的情況下,您希望提供其他值。
您收到此錯誤,因為如果您調用了MyClass(SomeType oneIn)
,則two
未初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.