Static block이 뭐지?

헌치·2022년 2월 24일
1
post-thumbnail

1. 자바에서 Static block이 뭐지??

  • Static block(static{...})
  • 클래스가 JVM에 처음 로드될 때 실행될 Java 클래스 내부의 명령문 블록
  • 생성자가 인스턴스 멤버를 초기화하는 것처럼, static 데이터(변수/상수)를 초기화
class Test{
 static {
 //Code goes here
 }
}

2. 예시

static block으로 a, b값 초기화

public class Demo {
 static int a;
 static int b;
 static {
    a = 10;
    b = 20;
 }
 public static void main(String args[]) {

  System.out.println("Value of a = " + a);
  System.out.println("Value of b = " + b);

 	}
}

결과값

Value of a = 10
Value of b = 20

3. 출처

Static Variable in Java: What is Static Block & Method [Example]
자매품 : 인스턴스 블록({})

profile
🌱 함께 자라는 중입니다 🚀 rerub0831@gmail.com

0개의 댓글