Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java immutable classes? [duplicate]

Tags:

java

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?
like image 530
javing Avatar asked Nov 23 '11 16:11

javing


2 Answers

Immutable classes are:

  • thread-safe by default (concurrent write never occurs)
  • cachable

You can read a lot about them in the conext of the language Java in Effective Java.

like image 27
zeller Avatar answered Nov 09 '22 22:11

zeller


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
like image 160
Santosh Avatar answered Nov 09 '22 21:11

Santosh