티스토리 뷰
이전글에서 non-static 블록을 알아보았고 이번글에서는 static 블록을 알아보겠습니다. static 블록은 non-static 블록 즉,{}에 static만 붙여준 것입니다. static{} 이런 형태입니다. 어떻게 사용되는지 살펴보면
class StaticBlock{
	StaticBlock(){
		System.out.println("Constructor called.");
	}
	static {
		System.out.println("Static Block called.");
	}
}
public class _118 {
	public static void main(String[] args) {
		StaticBlock b1 = new StaticBlock();
		StaticBlock b2 = new StaticBlock();
	}
}
결과
Static Block called. 
Constructor called. 
Constructor called.
차이점이 느껴지시나요? non-static 블록은 객체가 생성될때마다 호출이 되었는데 static 블록은 첫 번째 인스턴스를 생성하기 바로 전에 한 번만 수행됩니다. 인스턴스를 생성할때 또한 static 한 방법으로 호출되었을때 실행됩니다.
class StaticBlock1{
	static String result="";
	StaticBlock1(){
		System.out.println("Constructor called.");
	}
	static {
		System.out.println("Static Block called.");
	}
}
public class _118_1 {
	public static void main(String[] args) {
		System.out.print(StaticBlock1.result);
	}
}
결과
Static Block called.
이런식으로 클래스변수를 접근하려고 할때 호출됩니다. 객체생성이 되지 않았으니 생성자는 호출되지 않았구요.
class StaticBlock1{
	static String result="";
	StaticBlock1(){
		System.out.println("Constructor called.");
	}
	static {
		System.out.println("Static Block called.");
	}
}
public class _118_1 {
	public static void main(String[] args) {
		System.out.print(StaticBlock1.result);
		System.out.print(StaticBlock1.result);
	}
}
결과
Static Block called.
여러번 호출해도 static{} 블록은 최초 1번만 실행됩니다.
'ocjap를 위한 자바 기초 > 7 클래스와 객체' 카테고리의 다른 글
| 자바 {} non-static 블록 (0) | 2020.05.31 | 
|---|
					댓글
						
					
					
					
				
			
										공지사항
										
								
							
							
							
								최근에 올라온 글
								
							
							
								
									최근에 달린 댓글
									
							
							
								- Total
- Today
- Yesterday
									링크
									
							
							
								
									TAG
									
							
							
							- 라이믹스
- ocjap
- 파이썬
- proc
- EC
- webix
- xe addon
- 자바
- ocajp
- 플러터
- 인포믹스
- xe애드온
- KG
- Python
- JDBC
- MySQL
- C
- XE
- esql
- 자바 smtp
- 스크래핑
- 오라클
- 파싱
- 문자열
- 프로씨
- php
- 이클립스
- XE3
- 포인터
- C언어
| 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 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 | 
									글 보관함
									
							
					