final int和final static int之间的区别

use*_*347 2 java

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

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

jah*_*roy 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;
    }

}
Run Code Online (Sandbox Code Playgroud)