2017-11-06 1 views
2

클래스 Integerint 프리미티브 유형 (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 및 은 컴파일하는 코드를 찾는 것이 아니며, 이유는 무엇입니까?

+6

귀하의 질문에 귀하가 내부 클래스에 정적 인스턴스를 선언하고자한다는 사실을 지적하지 않습니다. ** 그 내부 클래스의 원시 상수를 선언 할 수 있다는 사실은 나를 음모에 빠뜨린다! ** – AxelH

+10

클래스'상수'는 비 정적 인 내부 클래스입니다. 정적 멤버는 가질 수 없습니다. – khelwood

+0

의견을 보내 주셔서 감사합니다. 이 경우 왜'public static final String'과'public static final int'를 선언 할 수 있습니까? – Bernat

답변

3

당신은 JLS에서이 뒤에 이유를 찾을 수 있습니다.

4.12.4. final Variables

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression

이것은 당신이 원시적 또는 String 상수를 선언 할 수 있습니다 이유 :

8.1.3. Inner Classes and Enclosing Instances

It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable (§4.12.4).

다음, 우리는 일정한 변수의 정의를 확인하실 수 있습니다 . 그러나 Integer 클래스 및 기타 권투 클래스는 예외의 일부가 아니며, 다른 클래스와 마찬가지로 인스턴스입니다.

출처 : Andy Thomas

인라인 일정

우리가 추가 한 경우 그 다음과 같은 :

13.1. The Form of a Binary

A reference to a field that is a constant variable (§4.12.4) must be resolved at compile time to the value V denoted by the constant variable's initializer.

우리는 일정한 사람들은 실제로 존재하지 않는 것을 알 수 있습니다 런타임에 참조는 컴파일 타임에 해결됩니다.

코드 :

final static int INTEGER_CONSTANT = 1; 
int value = INTEGER_CONSTANT; 

실행 시간 "코드"다음 JLS 당으로

int value = 1; 
4

문제는 상수의 선언이 아니라 정적이 아닌 내부 클래스에서 선언 된 사실입니다. 클래스의 선언을 정적으로 변경하면 좋은 것입니다.

public static class Constants { 
    public static final String STRING_CONSTANT = "string_constant"; 
    public static final int INTEGER_CONSTANT = 1; // allowed 
    public static final Integer INTEGER_CONSTANT1 = 1; 
    public static final Integer INTEGER_CONSTANT2 = new Integer("1"); 
    public static final Integer INTEGER_CONSTANT3 = Integer.valueOf(1); 
} 
+0

답변 해 주셔서 감사합니다. 그러나, 나는 코드에 대한 해결책을 찾고있는 것이 아니라, Integer가 허용되지 않고 String/int가되는 이유를 찾고있다. – Bernat

-1

정의를보세요. static final Integer의 문제는 아닙니다. 하지만 내부 (중첩 된) 클래스. 내부 클래스는 기본적으로 부모 클래스의 속성이며 수행해야 할 작업을 수행합니다. 이 기능을 다른 사람들이 볼 수있게 만들고 싶다면 클래스는 내부 클래스를 정적으로 만들고 코드가 작동합니다. 하지만 일부 전역 구성 클래스를 사용하려는 경우 하위 클래스로만 선언하십시오.

0

Java는 public static final Integer을 허용하지만 정적 내부 클래스는 허용하지 않습니다. 선언을 클래스 Ideone으로 옮기거나 클래스 Constants를 static으로 만듭니다. 초기화가 문자열 및 원시 형식에서만 작동하는 컴파일러 상수로 간주되는 경우에만 내부 클래스의 public static final 필드를 선언 할 수 있습니다.

public static final String a = new String("ds"); //will not work

관련 문제