ocajp 자격증 (Oracle Certified Associate Ja

ocjap 문제 해설 Static 61

xemaker 2020. 3. 5. 18:25
public class Static62 {
	int count;
	public static void displayMsg() {
		count++;
		System.out.println("Welcome "+"Visit Count: "+count);
	}
	
	public static void main(String[] args) {
		Static62.displayMsg();
		Static62.displayMsg();
	}
}

What is the result?

A. Compilation fails at line n3 and line n4.

B. Compilation fails at line n1 and line n2.

C. Welcome Visit Count:1

Welcome Visit Count: 1

D. Welcome Visit Count:1

Welcome Visit Count: 2

 

정답: B

결과:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
Cannot make a static reference to the non-static field count
Cannot make a static reference to the non-static field count

at Static62.displayMsg(Static62.java:4)
at Static62.main(Static62.java:9)

해설:

결과에 나온 메시지 대로

static 필드가 아닌 count 변수에 static 참조를 만들 수 없다.

즉, static 메소드에서 static 변수가 아닌 변수에 참조할 수 없다는 것이다.

static 메소드에서는 static 변수만 참조를 할 수 있다.

위의 예제에서는 int count; 대신에 static int count하면 에러가 안나고 정상실행된다.

static int count; 했을 경우 결과는

Welcome Visit Count: 1
Welcome Visit Count: 2