0

Is a class with only static members immutable? Or close to being immutable?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Sanjay Singh
  • 307
  • 1
  • 3
  • 13

2 Answers2

1

Techinically, yes.

Definition of immutability:

Immutable means that once the constructor for an object has completed execution that instance can't be altered.

Say you have this class:

public class MyClass {
    public static int a = 0;
}

When you create an instance of this class, you can't "alter" it, because there is nothing to alter, to change the value of! There are no non-static members!

So yeah, such a class is immutable.

Community
  • 1
  • 1
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 1
    Yes you can, but immutability is only to do with the instance members of the class, nothing to do with static members. MyClass is not an instance of MyClass. @LoganKulinski – Sweeper Nov 28 '16 at 13:52
1

If the fields are all final and primitive or immutable, then you have an immutable class. Note: just making a field final doesn't make it immutable.

// not immutable!
private static final Set<String> words = new HashSet<>();
public static void addWord(String word) { words.add(word); }

Note: one exception to this rule on immutable is use of reflection or native methods. Reflection/native methods can attempt to override even final values. One place this is used is in java.lang.System

public final static PrintStream out = null;

So you might conclude that System.out is always null and you can't write a Hello World program, but oh no this gets set from native code in a manner similar to what this method does

public static void setOut(PrintStream out) {
    checkIO();
    setOut0(out);
}
private static native void setOut0(PrintStream out);

So in fact, System.out does get reset by the JVM on startup and you can reset it using System.setOut

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130