Java构造函数最终变量赋值 [英] Java constructor final variable assignment

查看:421
本文介绍了Java构造函数最终变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
        }

编译器分别为3个变量赋值给出以下错误:
variable _email可能已经被赋值

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

编译器是否无法告诉变量在第一个ctor的调用中没有设置?我在这里缺少什么?

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

推荐答案

要添加到什么不可计数说,你可能想重构你的代码,使得具有较少参数的构造函数调用具有更多参数的构造函数,指定合理的默认值或null(视情况而定)。

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.

这篇关于Java构造函数最终变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆