# init과 clinit의 차이점

코드를 분석하다 보니 clinit 관련 내용을 확인하게 되었는데 init과 무슨 차이가 있나 궁금했다.

# 1.공식문서 설명

오라클 공식문서 (opens new window)에는 이렇게 설명되어있다.

2.9. Special Methods At the level of the Java virtual machine, every constructor (§2.12) appears as an instance initialization method that has the special name . This name is supplied by a compiler. Because the name is not a valid identifier, it cannot be used directly in a program written in the Java programming language. Instance initialization methods may be invoked only within the Java virtual machine by the invokespecial instruction, and they may be invoked only on uninitialized class instances. An instance initialization method takes on the access permissions (§2.7.4) of the constructor from which it was derived. A class or interface has at most one class or interface initialization method and is initialized (§2.17.4) by invoking that method. The initialization method of a class or interface is static and takes no arguments. It has the special name . This name is supplied by a compiler. Because the name is not a valid identifier, it cannot be used directly in a program written in the Java programming language. Class and interface initialization methods are invoked implicitly by the Java virtual machine; they are never invoked directly from any Java virtual machine inw2struction, but are invoked only indirectly as part of the class initialization process.

잘 읽어보아도 이해가 잘 안된다.

# 2.예시

stack overflow (opens new window)에 좋은 예시가 있다.

<init> is the (or one of the) constructor(s) for the instance, and non-static field initialization.

<clinit> are the static initialization blocks for the class, and static field initialization.

init은 인스턴스의 생성자이며 non-static(비 정적) 필드 초기화이고,

clinit은 클래스에 대한 static(정적) 초기화 블록 및 정적 필드 초기화라고 한다.

아래 코드를 보면 정확히 이해가 된다!

class X {

   static Log log = LogFactory.getLog(); // <clinit>

   private int x = 1;   // <init>

   X(){
      // <init>
   }

   static {
      // <clinit>
   }

}
Last Updated: 6/18/2023, 2:13:15 PM