开发者

Java constructor final variable assignment

public class User
{
     private final String   _first_name;
     private final String   _last_name;
     private final String   _org_ID;
     private final TimeZone _time_zone;
     private final InternetAddress _email;
     private final Date _last_login;
     private final Date _creation_date;


        public User( final String org_ID,
                             final String username,
                             final String first_name,
                             final String last_name,
                             final List<String> roles,
                             final TimeZone time_zone,
       开发者_Python百科                      final InternetAddress email,
                             final Date last_login,
                             final Date creation_date )
        {
            this( null, org_ID, username, first_name, last_name, roles, time_zone );

            this._email = email;
            this._last_login = last_login;
            this._creation_date = creation_date;
        }

The compiler gives the the following error for the 3 variable assignments respectively: "variable _email might already have been assigned"

Is the compiler unable to tell the variables are not set in the call to the first ctor? What am I missing here?


To add on to what irreputable said, you may want to refactor your code so that the constructor with fewer arguments calls the constructor with more arguments, specifying a reasonable default or null, as the case may warrant.

The reason you're getting the error is because the constructor with fewer arguments has to deal with the fields that aren't explicitly dealt with. However, if you flip the way the constructors are called, you will avoid this issue.


So the compiler isn't smart enough. Help it out.

Usually the constructor with less parameters calls the constructor with more parameters, not like yours.


You have declared the variables as final. Final variables cannot be set to another value after their initial assigment. Even by using a constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜