简体   繁体   English

Java构造函数最终变量赋值

[英]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,
                             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" 编译器分别为3个变量赋值给出以下错误:“变量_email可能已经被分配”

Is the compiler unable to tell the variables are not set in the call to the first ctor? 编译器无法告诉变量是否未在第一个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. 要添加到无可争议的内容 ,您可能需要重构代码,以便具有更少参数的构造函数使用更多参数调用构造函数,指定合理的默认值或null,视情况而定。

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。 Final variables cannot be set to another value after their initial assigment. 在最初的分配后,最终变量不能设置为另一个值。 Even by using a constructor. 即使使用构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM