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.