java – 调用super()必须是构造函数体中的第一个语句
|
我正在编写一个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,Response.ErrorListener errorListener) {
super((username!=null && password!=null)? Method.POST:Request.Method.GET,errorListener);
this.username=username;
this.password=password;
}
但这不是有效的完全相同的事情吗? call-super-constructor-must-first-statement语句规范是否比它需要的更简单,或者我错过了什么? 编辑:这被错误地标记为Why do this() and super() have to be the first statement in a constructor?的重复.这个问题更通用,并询问为什么super()必须是第一个声明.这里的问题是为什么像我发布的那样的案例会破坏这些要求(并且在这个问题中得到了令人满意的回答) 解决方法Java强制要求对super(显式或非显式)的调用必须是构造函数中的第一个语句.这是为了防止在初始化对象的超类部分之前初始化对象的子类部分.在你的情况下,你除了本地的“琐碎的计算”之外什么都不做,所以考虑到所有事情,它都没关系.但是,Java的编译器没有达到确定调用super之前的语句是否实际进行任何初始化的程度.它只是不允许在super()之前的所有语句. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
