클래스 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를 선언함으로써 우리는 보장 할 수있는 사항은 다음과 같습니다
Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.
을 또 다시, immutable 문서에 의해 :
그래서An object is considered immutable if its state cannot change after it is constructed.
최종 불변 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
및 은 컴파일하는 코드를 찾는 것이 아니며, 이유는 무엇입니까?
귀하의 질문에 귀하가 내부 클래스에 정적 인스턴스를 선언하고자한다는 사실을 지적하지 않습니다. ** 그 내부 클래스의 원시 상수를 선언 할 수 있다는 사실은 나를 음모에 빠뜨린다! ** – AxelH
클래스'상수'는 비 정적 인 내부 클래스입니다. 정적 멤버는 가질 수 없습니다. – khelwood
의견을 보내 주셔서 감사합니다. 이 경우 왜'public static final String'과'public static final int'를 선언 할 수 있습니까? – Bernat