0

At the following URL: Java Programming/Keywords/public

The following Class is describes an immutable public class named Length. My question is since it's public, doesn't that defeat the object of trying to make it immutable? Shouldn't an immutable class be declared as final ? I see typical advice regarding immutable classes given elsewhere as follows:

Make your class final, so that no other classes can extend it.

package org.wikibooks.java;

public class Length {
   private double magnitude;
   private String units;

   public Length(double magnitude, String units) {
      if ((units == null) || (units.trim().length() == 0)) {
          throw new IllegalArgumentException("non-null, non-empty units required.");
      }

  this.magnitude = magnitude;
  this.units = units;
   }

   public double getMagnitude() {
      return magnitude;
   }

   public String getUnits() {
      return units;
   }

}
Russell
  • 99
  • 7
  • It is immutable because it doesn't provide mutators (setter methods), but, yes, if the final intent is to make it immutable, it should be declared final or constructors private (maybe protected, depending on the specific scenario) – lealceldeiro Jan 01 '20 at 10:41
  • Thanks for that. I'm learning, so that confirms what I had thought. - – Russell Jan 01 '20 at 10:57
  • You should probably make `units` an enum; unless it is somehow meaningful that you can supply `"m"`, `"metres"`, `"meters"`, `"kilometres"`, `"barleycorns"`, `"smoot"` etc. – Andy Turner Jan 01 '20 at 11:07

0 Answers0