0

Does anyone know how to add methods to an immutable class which allows me to modify the object specified upon initialization only?

For example you have 2 numbers which you want to be able to multiply by a factor.

so when initialising you want to also be able to multiply if you wish to

Class name_of_object = new class(int1, int2).multiply_method(intfactor);

and that would create an object which cannot be modified?

  • 1
    You can use builder pattern to create your objects... https://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern – derUser Mar 11 '19 at 18:24
  • Java makes some guarantees about final fields that are assigned by the time the constructor completes, so you don't want to do it that way. Use the builder pattern or perform the operation within the constructor itself or from a private final helper method. – David Conrad Mar 11 '19 at 18:53

1 Answers1

0

Simply: you can't.

If you somehow modify the fields of an immutable class, then you have proven that it wasn't immutable.

If it's your own class, then of course you can allow for changes after construction, by writing appropriate methods, this way making the class mutable.

If you want to keep your class immutable, you can have the modifying method return a fresh instance of your class, with the changed field values (like e.g. BigInteger.add()). The original instance stays unchanged, and you get a new one with the desired values.

If it's someone else's immutable class, you can't change it. You have to deal with its methods.

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7