0

I am trying to understand immutability without setters. To model a class Person , I generally has variables like name,age,sex and others along with setters and getters. If I want to change the age in future, I can simply call the age setter on the object.

How do I model same thing for a class without setters?.In general I may require to change the age of person, but immutability does now allow it.

mc20
  • 1,145
  • 1
  • 10
  • 26
  • 2
    Create a new `Person` with a different `age`. – Sotirios Delimanolis Oct 14 '15 at 00:31
  • 2
    `String` would be an example for immutable objects in java. There are no methods that directly modify the string itself. Instead, if you want to manipulate a string, you'll have to generate a new one that contains the manipulated content. Though there are quite a lot of problems that can be solved without generating any new objects. e.g. the problem with updating the age in your question can be solved by simply storing the birthdate instead of the age –  Oct 14 '15 at 00:35
  • 2
    This is not a duplicate. The poster is asking how to "change" an immutable object's value. The linked "duplicate" answers why immutable is good. – Steve Kuo Oct 14 '15 at 00:40
  • 1
    From the accepted answer in the duplicate post: _if you need to "change" an immutable object, you can create a new one from the old one:_ I feel that answers this question. – Sotirios Delimanolis Oct 14 '15 at 00:42

0 Answers0