2

可能重复:
java:使用最终静态 int = 1 是否比普通 1 更好?

好吧,我想知道之间有什么区别: final int a=10; 和最终静态int a = 10;当它们是类的成员变量时,它们都具有相同的值,并且在执行期间不能随时更改。除了静态变量由所有对象共享并且在非静态变量的情况下创建副本之外,还有其他区别吗?

4

5 回答 5

10

如果在声明变量时对其进行初始化,则没有实际区别。

如果变量是在构造函数中初始化的,那么会有很大的不同。

请参见下面的示例:

/** 
 *  If you do this, it will make almost no 
 *  difference whether someInt is static or 
 *  not.
 *
 *  This is because the value of someInt is
 *  set immediately (not in a constructor).
 */

class Foo {
    private final int someInt = 4;
}


/**
 *  If you initialize someInt in a constructor,
 *  it makes a big difference.  
 *
 *  Every instance of Foo can now have its own 
 *  value for someInt. This value can only be
 *  set from a constructor.  This would not be 
 *  possible if someInt is static.
 */

class Foo {
    private final int someInt;

    public Foo() {
        someInt = 0;
    }

    public Foo(int n) {
        someInt = n;
    }

}
于 2012-11-20T02:11:35.930 回答
2

静态变量可以通过类定义之外的点分隔符访问。因此,如果您有一个名为 myClass 的类,并且在其中您有 static int x = 5; 然后你可以用 myClass.x 来引用它;

final 关键字意味着在定义 x 之后,您不能更改它的值。如果您尝试这样做,编译器将停止并出现错误。

于 2012-11-20T02:12:07.427 回答
0

我要指出的是,静态修饰符只能用于明确的需求,而 final 只能用于常量。

于 2012-11-20T02:33:33.350 回答
0

作为static变量,您不需要类的实例来访问该值。唯一的其他区别是该static字段未序列化(如果类是可序列化的)。也有可能编译代码中对它的所有引用都被优化掉了。

于 2012-11-20T02:11:50.580 回答
0

int如果您只使用s ,则差异不会出现。然而,作为一个例子,它是如何不同的:

class PrintsSomething {
   PrintsSomething(String msg) {
       System.out.println(msg);
   }
}

class Foo {
    public static final PrintsSomething myStaticObject = new PrintsSomething("this is static");
    public final PrintsSomething myLocalObject = new PrintsSomething("this is not");
}

当我们运行这个:

new Foo();
new Foo();

...输出是这样的:

this is static
this is not
this is not
于 2012-11-20T02:25:07.197 回答