通过静态字段创建实例

use*_*882 3 java static

我有以下两个类:

public class A{
    private String s;
    public A(String s){
        this.s = s;
    }
}

public class B{
    private static final String STR = "String";

    public void doAction(){
        A a = new A(STR); //Does it look really wierd?
    }
}
Run Code Online (Sandbox Code Playgroud)

我从未将静态final字段作为构造函数参数传递,因此它是否会导致潜在的错误?我们应该避免它,或者我们可以做到这一点,如果它看起来简洁.

das*_*ght 7

我从未将静态final字段作为构造函数参数传递,因此它是否会导致潜在的错误?

这不会导致错误,因为它doAction是一个实例方法.具有初始值设定项的所有静态字段将在调用第一个实例方法之前初始化,因此您是安全的.

我们应该避免它,或者如果看起来简洁,我们可以做到吗?

String在实例方法中使用静态最终字段(实际上是常量)是完全有效的选择.