简体   繁体   English

只有静态成员的类是不可变的吗?

[英]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. 如果这些字段都是final且是原始的或不可变的,则您具有不可变的类。 Note: just making a field final doesn't make it immutable. 注意:仅将字段定为final不会使其不变。

// 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 一个使用的地方在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 因此,您可能会得出以下结论: System.out始终为null并且无法编写Hello World程序,但是,哦,不,它是通过本机代码来设置的,类似于此方法的操作方式

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 所以实际上, System.out确实会在启动时被JVM重置,您可以使用System.setOut重置它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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