final - What steps can you make to make a java object with a setter to be immutable? -
this question has answer here:
- how final keyword works 17 answers
what can make object such immutable? concerned solving public void somemethod(someobject someobject) { }
<== case
for example:
public class someobject { private string somestring; public void setsomestring(string somestring) { this.somestring = somestring; } public void getsomestring() { return somestring; } } public void somemethod() { final someobject someobject = new someobject(); someobject.set("want prevent this"); // <-- someobject mutable in case } public void somemethod(someobject someobject) { someobject.set("and prevent this!"); // <-- , }
you right, declaring object final
not make immutable. preventing final
variable being re-assigned new object, object assigned mutated if mutating methods available.
you can give object interface immutable, , program interface:
interface immutablecar { string getmake(); string getmodel(); } class car implements immutablecar { public car(string make, string model) { this.make = make; this.model = model; } private string make; private string model; public string getmake() { return make; } public void setmake(string m) { make = m; } public string getmodel() { return model; } public void setmodel(string m) { model = m; } }
if this
immutablecar car = new car("vw", "bora");
you not able access mutating methods without explicit cast. of course not make object immutable, because casting remain possibility, 1 argue other immutable objects can changed going through reflection, approach lets expose immutable behavior.
Comments
Post a Comment