티스토리 뷰

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

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함