我正在编写一个LoginRequest类的构造函数,该类扩展了一个名为JsobObjectRequest的类(来自Android的Volley框架,但这与问题完全无关)
使用此代码:
public LoginRequest(String username, String password, Response.Listener 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 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;
}
但这实际上不是一回事吗?在这两种情况下,根据传递给子类构造函数的参数值,在调用超级构造函数之前都要进行一些简单的计算。鉴于编译器可以编译第二个示例,为什么它不能编译第一个示例?
调用超级构造函数必须是第一个陈述的规范比它需要的简单得多,还是我错过了一些东西?
编辑
:这被错误地标记为重复为什么this()和super()必须是构造函数中的第一条语句?。这个问题更加通用,并问为什么super()必须是第一个语句。这里的问题是,为什么像我所发布的那样一个案例不能满足这些要求(并且在这个问题中得到了令人满意的回答)