본문 바로가기

Hello World!!/Java

static 메소드의 제약 조건

 - static 메소드는 오직 static 멤버만 접근할 수 있다.

class StaticMethod {
	int n;
	void f1(int x) { n = x; } //정상
	void f2(int x) { m = x; } //정상
	
	static int m;
	static void s1(int x) { n = x; } //컴파일 오류. static 메소드는 non-static 필드 사용 불가
	static void s2(int x) { f1(3); } //컴파일 오류. static 메소드는 non-static 메소드 사용 불가
	
	static void s3(int x) { m = x; } // 정상
	static void s4(int x) { s3(3); } // 정상
}


 - static 메소드에서는 this 키워드를 사용할 수 없다.

class StaticAndThis {
	int n;
	static int m;
	void f1(int x) { this.n = x; } // 정상
	void f2(int x) { this.m = x; } // non-static 메소드에서는 static 멤버 접근 가능
	static void s1(int x) { this.n = x; } // 컴파일 오류. static 메소드는 this 사용 불가
}

'Hello World!! > Java' 카테고리의 다른 글

final  (0) 2013.10.23
static 멤버와 non-static 멤버의 차이  (0) 2013.10.23
메소드 오버로딩 조건  (0) 2013.10.23
접근 지정자  (0) 2013.10.23