Java immutable classes? [duplicate]

I found an article with an interesting piece of code:

public class Employee {

    private String firstName;
    private String lastName;

    //private default constructor
    private Employee(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public static Employee valueOf (String firstName, String lastName) {
        return new Employee(firstName, lastName);
    }
}

I am really curious in understanding the advantage of creating this kind of classes.
I understand that here that an object of this class would be immutable, because there is no way of changing its variable values once initialized. I never did something like this before, and i dont really understand the advantage of it.

  • Why is it a good practice?
  • Could you name a situation where this approach can be used?
  • What about constants or read only variables? Is not that very similar?
  • In the article says, that this is not good for the performance of the application. But why?

Answer

The example you have mentioned is of an Immutable Objects. Its widely used concepts in programming languages.

Quoting from the link above. The advantages are

  • are simple to construct, test, and use
  • are automatically thread-safe and have no synchronization issues
  • do not need a copy constructor
  • do not need an implementation of clone
  • allow hashCode to use lazy initialization, and to cache its return value
  • do not need to be copied defensively when used as a field
  • make good Map keys and Set elements (these objects must not change state while in the collection)
  • have their class invariant established once upon construction, and it never needs to be checked again
  • always have “failure atomicity” (a term used by Joshua Bloch) : if an immutable object – throws an exception, it’s never left in an undesirable or indeterminate state

Attribution
Source : Link , Question Author : javing , Answer Author : Santosh

Leave a Comment