user5910494
user5910494

Reputation:

Creating Immutable Classes with Multiple Constructors

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

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?

This closest I've come is this:

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?

Upvotes: 3

Views: 853

Answers (2)

rgettman
rgettman

Reputation: 178263

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.

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.

Upvotes: 5

najkbar
najkbar

Reputation: 1

You need to either call the second Person(first, last, age) constructor inside your first constructor, or you need to set this.personAge to some default value inside your first constructor.

As of now if someone were to declare a Person using the first constructor, then the final int personAge would not have a value.

Upvotes: 0

Related Questions