[英]Constructor error “call to this must be first statement in constructor”
[英]“Constructor call must be the first statement in a constructor” error
我試圖做一個構造函數,它接受一個字符串並構造一個日期對象。 到目前為止,這是我的解決方案,但出現此錯誤:
構造函數調用必須是構造函數中的第一條語句
private int m;
private int d;
private int y;
private String[] dateStrings;
public Date(int month, int day, int year) {
m = month;
d = day;
y = year;
}
public Date(String s) {
dateStrings = s.split("/");
this(Integer.parseInt(dateStrings[0]), Integer.parseInt(dateStrings[1]), Integer.parseInt(dateStrings[2]));
}
我意識到我需要this(...)
,但是當我需要首先填充dateStrings時該怎么做? 如何避免此錯誤? 注意:要使用字符串構造日期,其格式應為“月/日/年”
this()
需要被調用。
而是將分配移動到私有方法。
private void assginValues (int month, int day, int year){
m = month;
d = day;
y = year;
}
如果還需要填充dateStrings
,則也可以在此方法中進行構建。
然后從兩個構造函數調用該方法。 確保共享字符串的構造函數不會調用this()
因為共享方法將負責分配值。
您也可以在一行中完成所有操作,但是隨后您多次調用split()
,這很浪費 :
this(Integer.parseInt(s.split("/")[0]), Integer.parseInt(s.split("/")[1]), Integer.parseInt(s.split("/")[2]));
我發現最好的避免方法是使用靜態工廠
public static Date MakeDate(String s) {
dateStrings = s.split("/");
return new Date(Integer.parseInt(dateStrings[0]), Integer.parseInt(dateStrings[1]),
Integer.parseInt(dateStrings[2]));
}
並且出於不變性的考慮,我可能會重載它,而只是避免擁有一個工廠和一個構造函數的整個怪異。
private Date(int month, int day, int year) {
m = month;
d = day;
y = year;
}
public static MakeDate(int mont, int day, int year){
//You can figure this part out
}
這樣做的一個好處是,您可以對這些工廠進行不同的命名,以明確其意圖。 在這種情況下可能不是必需的,但是它是一個不錯的選擇,尤其是對於更復雜的類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.