我正在编写一个 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;
}
但这实际上不是完全相同的事情吗?
在这两种情况下,在调用超级构造函数之前,都会根据传递给子类构造函数的参数值进行一些简单的计算。既然编译器可以编译第二个示例,为什么它不能编译第一个示例?
调用超级构造函数必须是第一个语句规范是否比它需要的更简单,或者我错过了什么?
EDIT:这已被错误地标记为重复项为什么 this() 和 super() 必须是构造函数中的第一个语句?。这个问题更加通用,它询问为什么 super() 必须是第一个语句。这里的问题是为什么像我发布的那样的案例会满足这些要求(并且在这个问题中已经得到了令人满意的回答)