简体   繁体   中英

Is a class with only static members immutable?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM