Hello World!!/Java

static 메소드의 제약 조건

옹알 2013. 10. 23. 16:41

 - 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 사용 불가
}