创建具有多个构造函数的不可变类 [英] Creating Immutable Classes with Multiple Constructors

查看:88
本文介绍了创建具有多个构造函数的不可变类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读此页面有关创建不可变类的信息Java中,并决定修改我正在编写的类以符合页面上概述的规范.

I'm reading this page on creating immutable classes in Java, and decided to modify a class I was writing to the specifications outlined on the page.

final String personfirstname;
final String personlastname;
final int personAge;

public Person(String firstname, String lastname) {

   this.personfirstname = firstname;
   this.personlastname = lastname;
}

public Person(String firstname, String lastname, int personAge){
    this(firstname,lastname);

    this.personAge = personAge;
}

我的问题是,eclipse表示可能未设置personAge,尽管我在第二个构造函数中进行了设置.用java中的两个构造函数创建不可变类是不可能的吗?如果可能的话我该怎么办?

My issue is, eclipse says that the personAge may not have been set, despite the fact that I'm doing so in the second constructor. Is it not possible to create an immutable class with two constructors in java? If it's possible how would I do it?

我来的最接近的是这个

final private String personfirstname;
final private String personlastname;
final private int personAge;

public Person(String firstname, String lastname) {

    this.personfirstname = firstname;
    this.personlastname = lastname;
    //Set a default age
    this.personAge = 0;

}

public Person(String firstname, String lastname, int age){

    this.personfirstname = firstname;
    this.personlastname = lastname;
    this.personAge=age;
}

我提供了默认年龄,但是,我的构造函数没有链接,可以吗?如果没有,我将如何在一个不可变的类中提供两个构造函数?

I provided a default age, BUT my constructors aren't chained, is this okay? If not, how would I provide two constructors in an immutable class?

推荐答案

用户可以调用第一个构造函数,而该构造函数根本没有设置personAge. final变量必须在构造函数的末尾明确分配,但不是.

A user can call the first constructor, which doesn't set personAge at all. The final variable must be definitely assigned by the end of the constructor, and it isn't.

在一个构造函数中切换personfirstnamepersonlastname的分配,并在另一个构造函数中调用this构造函数.这样,第一个构造函数将委派给第二个构造函数以执行所有操作,包括设置年龄.

Switch the assignments of personfirstname and personlastname in one constructor with the call to the this constructor in the other. This way, the first constructor delegates to the second constructor to do everything, including setting the age.

public Person(String firstname, String lastname) {
    // or another reasonable default value for age
    this(firstname, lastname, 0);  
}

public Person(String firstname, String lastname, int personAge){
    this.personfirstname = firstname;
    this.personlastname = lastname;
    this.personAge = personAge;
}

构造函数保持链接状态,因此不会重复代码.所有字段都分配在一起,并且在对任何构造函数的调用结束时,肯定将所有字段都分配了.

The constructors remain chained, so no code is duplicated. All fields are assigned together, and all fields are definitely assigned at the end of a call to any constructor.

这篇关于创建具有多个构造函数的不可变类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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