Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java final int和final static int之间的差异_Java - Fatal编程技术网

Java final int和final static int之间的差异

Java final int和final static int之间的差异,java,Java,可能重复: 我想知道以下两者之间的区别: 最终INTA=10; 及 最终静态积分a=10; 当它们是类的成员变量时,它们都具有相同的值,并且在执行过程中不能随时更改。 除了静态变量由所有对象共享以及在非静态变量的情况下创建副本之外,还有其他区别吗?如果在声明变量时初始化变量,则没有实际区别 如果变量在构造函数中初始化,则会产生很大的差异 请参见下面的示例: /** * If you do this, it will make almost no * difference wheth

可能重复:

我想知道以下两者之间的区别: 最终INTA=10; 及 最终静态积分a=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;
    }

}

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

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


final关键字表示在定义x后不允许更改x的值。如果您尝试执行此操作,编译器将因错误而停止。

如果您仅使用
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

我要指出的是,静态修饰符只能用于显式需求,而最终修饰符只能用于常量

您的示例没有演示静态变量和非静态变量之间的区别,因为您在声明变量时就设置了它的值。请参阅我的答案,以了解何时存在差异。伟大的答案显示了关键(通常被忽略)差异+1+1如果您有一个永远不会像这样更改的字段,JVM可以对其进行优化,使其
静态
,这样您甚至不会在每个对象中浪费内存。IMHO
static
更清楚地表明这不是一个错误。事实上,如果您试图分配给
final
变量,编译器会抱怨。它甚至不会抛出错误(这是一个运行时事件),Java也不会“警告”您。编译器将因错误而停止。