![](/img/trans.png)
[英]Constructor call must be the first statement in a constructor in super()
[英]call to super() must be the first statement in constructor body
我正在編寫一個LoginRequest類的構造函數,該類擴展了一個名為JsobObjectRequest的類(來自Android中的Volley框架,但這與問題完全無關)
使用此代碼:
public LoginRequest(String username, String password, Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
Boolean hasCredentials=(username!=null && password!=null);
int method=hasCredentials? Method.POST:Request.Method.GET;
super(method, API_URL_LOGIN, null, responseListener, errorListener);
this.username=username;
this.password=password;
}
我得到錯誤:調用super()必須是構造函數體中的第一個語句
相反,這段代碼編譯得很好:
public LoginRequest(String username, String password, Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
super((username!=null && password!=null)? Method.POST:Request.Method.GET, API_URL_LOGIN, null, responseListener, errorListener);
this.username=username;
this.password=password;
}
但這不是有效的完全相同的事情嗎? 在這兩種情況下,在調用超級構造函數之前,根據傳遞給子類構造函數的參數值,進行一些簡單的計算。 為什么編譯器不能編譯第一個例子,因為它可以編譯第二個例子?
call-super-constructor-must-first-statement語句規范是否比它需要的更簡單,或者我錯過了什么?
編輯 :這被錯誤地標記為重復為什么this()和super()必須是構造函數中的第一個語句? 。 這個問題更通用,並詢問為什么super()必須是第一個聲明。 這里的問題是為什么像我發布的那樣的案例會破壞這些要求(並且在這個問題中得到了令人滿意的回答)
Java強制要求對super
(顯式或非顯式)的調用必須是構造函數中的第一個語句。 這是為了防止在初始化對象的超類部分之前初始化對象的子類部分。
在你的情況下,除了本地的“瑣碎計算”之外你什么都不做,所以考慮到所有事情,它都沒關系。 但是,Java的編譯器沒有達到確定調用super
之前的語句是否實際進行任何初始化的程度。 它只是在super()
之前不允許所有語句。
此語句為true.super()必須始終是子類構造函數內執行的第一個語句。 。 有關詳細信息,請參閱Herbert Schildt的完整參考資料...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.