Immutable object in Java

Question:

In java all object can be mutable and immutable . It is clear that, for example, a string is immutable . But if I want to create my own immutable type, what requirements should it fulfill?

I have an example like this:

public class ImmutableObject {

    private final String string;
    private final Date date;

    public ImmutableObject(String string, Date date) {
        this.string = string;
        this.date = date;
    }

    public Date getDate() {
        return new Date(date.getTime());
    }

    public String getString() {
        return string;
    }

}

Can I consider it immutable? Do fields have to be final ? And if one of the fields, for example a string, is not final , then an object of this class can be considered immutable? Does this class take into account all the pitfalls of multithreading?

Answer:

Yes, fields must be final .

I would not equate an Immutable object with an object that has read-only methods. The fact is that as an optimization, the compiler can easily rearrange the lines with instructions, this is the so-called reordering. As a result, it may happen that your object will be accessible from other threads, but its variables may not be initialized. In single-threaded applications, this is, in principle, not scary, but if you work in a multi-threaded environment, then final will protect your variables from such permutations.

Now on the merits of your questions:

  1. Yes, objects in your class can be considered immutable.
  2. Required in a multi-threaded environment.
  3. If the string is not final, then such an object is no longer Immutable.
Scroll to Top