0

Java immutable classes can be created by declaring it by

  1. Declaring class final.
  2. Declaring all member fields final.
  3. With no setters.

If there are no setters and class is declared final why should we set members final?

And also, Can i say, if a class is Immutable means it is thread safe?

Kalpesh Dusane
  • 1,477
  • 3
  • 20
  • 27
aspxsushil
  • 514
  • 1
  • 5
  • 16
  • 2
    Possible duplicate of [Immutable objects are thread safe, but why?](http://stackoverflow.com/questions/9303532/immutable-objects-are-thread-safe-but-why) – Dez Sep 26 '16 at 05:54
  • .If there are no setters and class is declared final why should we set members final? this is my major question here – aspxsushil Sep 26 '16 at 05:56

1 Answers1

1

If there are no setters and class is declared final why should we set members final?

To avoid the internal state to be modified internally. The following class looks immutable from the outside and we expect a call to getBar() to be side-effects free (it means whenever in time we call this method, we expect the same result, also known as determinism). However it's not, because calling doThing() has a side-effect on bar.

public final class Foo {
    private int bar;

    public Foo(int bar) {
        this.bar = bar;
    }

    public int getBar() {
        return bar;
    }

    public void doThing() {
        //do some things

        //increment bar for some reason
        bar++;
    }
}

If bar was final the code above wouldn't compile.

Can i say, if a class is Immutable means it is thread safe?

Not necessarly but in many cases yes.

Spotted
  • 4,021
  • 17
  • 33