Java – the call to super () must be the first statement in the constructor body
I'm writing a constructor for the loginrequest class, which extends a class called jsobobjectrequest (from the volley framework in @ l_502_0 @, but this has nothing to do with the problem)
Use this Code:
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; }
I got the error: the call to super () must be the first statement in the constructor body
Instead, the code compiles well:
public LoginRequest(String username,Response.ErrorListener errorListener) { super((username!=null && password!=null)? Method.POST:Request.Method.GET,errorListener); this.username=username; this.password=password; }
But isn't that the exact same thing that works? In both cases, some simple calculations are performed based on the parameter values passed to the subclass constructor before calling the super constructor Why can the compiler compile the first example because it can compile the second example?
Is the call super constructor must first statement specification simpler than it needs, or what am I missing?
Edit: This is incorrectly marked as why do this() and super() have to be the first statement in a constructor? Repetition of This question is more general and asks why super () must be the first declaration The question here is why a case like the one I published would undermine these requirements (and get a satisfactory answer to this question)
Solution
Java enforces that the call to super (explicit or non - explicit) must be the first statement in the constructor This prevents the subclass part of an object from being initialized before the superclass part of the object is initialized
In your case, you do nothing but local "trivial computing", so considering everything, it doesn't matter However, the java compiler does not determine whether the statement before calling super actually initializes It just doesn't allow all statements before Super ()