2013-08-11 10 views
-3
public class HelloWorld{ //Why is it throwing error here 
    final static int i; 
    public static void main(String []args){ 
     int i = call(10); 
     System.out.println("Hello World"+i); 
    } 
    static int call(int y){ 
     int r= y; 
     return r ; 
    } 
} 

위의 프로그램에서 final static int i;을 사용하면 오류가 발생합니다. 아무도 정확히 왜 저에게 말할 수 있습니까? 같은 final static int i;은 메서드 내에서 선언 할 때 잘 동작합니다.변수가 변수를 초기화하지 않았을 수 있음

오류 : 즉,이 행동하도록되어 방법이기 때문에

$javac HelloWorld.java 2>&1 
HelloWorld.java:1: error: variable i might not have been initialized 
public class HelloWorld{ 
^ 
1 error 

답변

4

당신은 오류를 얻고있다. JLS - Section 8.3.1.2에서

:

It is a compile-time error if a blank final (§4.12.4) class variable is not definitely assigned (§16.8) by a static initializer (§8.7) of the class in which it is declared.

그리고 당신이 가지고 있기 때문에, 지금 JLS - Section 16.8

Let C be a class, and let V be a blank static final member field of C, declared in C. Then:

  • V is definitely unassigned (and moreover is not definitely assigned) before the leftmost enum constant, static initializer (§8.7), or static variable initializer of C.

에서이 둘 정적 초기화,도 아니다 정적 변수 초기화은 최종 필드가 명확하게 할당되지 않는다 .

final static int i = 0; 

또는 static 블록 (정말 여기 필요하지 않습니다)에

:

final static int i; 
static { i = 0; } 
2

final 변수가 적어도 초기화해야

당신은 선언의 시점에서 i 몇 가지 값 중 하나를 지정해야합니다 기본값으로 설정합니다.

final static int i=0;//initialization at the time of declaration 

또는

final static int i; 

static{ 
    i=0;//initialization in static block 
} 
1

같은뿐만 아니라 비 정적 변수에 간다처럼

static final variables should be initialized before class loading completes.That is you can initialize them at the time of declaration or in static blocks.

그래서 최종 변수는 있어야한다. 0으로 초기화하면 괜찮습니다.

final static int i= 0; 

그러나 그림자가 있습니다. i을 새로 선언하고 사용하십시오. 귀하의 최종 i은 전혀 사용되지 않습니다.

0

에 관심이있을 수있는 몇 가지 값은 일부 int value

final static int i;를 초기화한다
관련 문제