Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to set several variables at once just define a function:</p> <pre><code>public class Person { public Person(String firstName, String lastName, Date dateOfBirth) { set(firstName, lastName, dateOfBirth); } public void set(String firstName, String lastName, String dateOfBirth) { ... } } </code></pre> <p>By definition an object is only constructed once, hence the constructor is only called once.</p> <p>One thing worth noting: it's more common to favour immutability, so:</p> <pre><code>public class Person { private final String firstName; private final String lastName; private final Date dateOfBirth; public Person(String firstName, String lastName, Date dateOfBirth) { this.firstName = firstName; this.lastName = lastName; this.dateOfBirth = dateOfBirth == null ? null new Date(dateOfBirth.getTime()); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public Date getDateOfBirth() { return dateOfBirth == null ? null : new Date(dateOfBirth.getTime()); } public Person withFirstName(String firstName) { return new Person(firstName, lastName, dateOfBirth); } public Person withLastName(String lastName) { return new Person(firstName, lastName, dateOfBirth); } public Person withDateOfBirth(Date dateOfBirth) { return new Person(firstName, lastName, dateOfBirth); } } </code></pre> <p>because a lot of concurrency issues simply go away when you do this. Not just concurrency issues too. <code>String</code>, <code>BigDecimal</code>, <code>BigInteger</code> and some other standard classes are immutable (immutable means once instantiated its state can never change). <code>Date</code> isn't. You see in the above code I have to constantly defensively copy the date of birth? That's because <code>Date</code> is not immutable. If you didn't a caller could do this:</p> <pre><code>public class Person { private final Date dateOfBirth; ... public Date getDateOfBirth() { return dateOfBirth; } } Person person = new Person(...); Date date1 = person.getDateOfBirth(); date1.setTime(1000000000L); System.out.println(person.getDateOfBirth()); </code></pre> <p>The date of birth will have changed. That problem is caused solely by <code>Date</code> being mutable. That's another reason to favour immutability.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload