【发布时间】:2018-04-18 14:30:38
【问题描述】:
Integer 类是 int 原始类型 (https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html) 的包装器。如果对象的状态在构造后无法更改,则该对象被认为是不可变的 (https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html)。
我在这里的理解是,您只能通过引用完全不同的 Integer 对象来更改 Integer 变量的值。
通过声明变量final,我们可以确保以下几点:
一旦分配了最终变量,它总是包含相同的值。如果最终变量持有对对象的引用,则对象的状态可能会通过对对象的操作而改变,但变量将始终引用同一个对象。
再一次,通过immutable 文档:
一个对象被认为是不可变的,如果它的状态在构造之后不能改变。
因此,最终的、不可变的Integer将不允许以任何方式更改其值。
如果这是正确的,为什么不允许我们声明 public static final Integer 变量?
following code 以不同的方式声明public static final Integer,它们都返回编译时错误:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public class Constants {
public static final String STRING_CONSTANT = "string_constant";
public static final int INTEGER_CONSTANT = 1; // allowed
//public static final Integer INTEGER_CONSTANT = 1; // not allowed
//public static final Integer INTEGER_CONSTANT = new Integer("1"); // not allowed
//public static final Integer INTEGER_CONSTANT = Integer.valueOf(1); // not allowed
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("STRING_CONSTANT = " + Constants.STRING_CONSTANT);
System.out.println("INTEGER_CONSTANT = " + Constants.INTEGER_CONSTANT);
}
}
抛出的异常是:
Main.java:12: error: Illegal static declaration in inner class Ideone.Constants
public static final Integer INTEGER_CONSTANT = 1;
^
modifier 'static' is only allowed in constant variable declarations
1 error
谁能解释一下为什么不允许我们声明public static final Integer?
编辑:我很想知道为什么 public static final Integer 是不允许的,而 public static final String 和 public static final int 是不允许的,而不是寻找可以编译的代码。
【问题讨论】:
-
您的问题并没有指出您要在内部类中声明静态实例的事实。 您可以在该内部类中声明原始常量这一事实确实引起了我的兴趣!
-
你的类
Constants是一个非静态内部类。它不能有静态成员。 -
感谢您的 cmets。在那种情况下,为什么我们可以声明
public static final String和public static final int? -
我猜编译器正在内联编译时常量,所以你可以避免通常不允许的事情。
Integer可以是运行时常量,但不是编译时常量,因此它不起作用。
标签: java static immutability final