Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

자바의 이니셜라이저 블록

<시간/>

Initializer 블록은 생성자의 공통 부분을 선언하는 데 사용됩니다. 예를 들어 보겠습니다 -

import java.io.*;
public class Demo{
   {
      System.out.println("The common constructor has been invoked");
   }
   public Demo(){
      System.out.println("The default constructor has been invoked");
   }
   public Demo(int x){
      System.out.println("The parametrized constructor has been invoked");
   }
   public static void main(String arr[]){
      Demo my_obj_1, my_obj_2;
      System.out.println("The Demo objects have been created.");
      my_obj_1 = new Demo();
      my_obj_2 = new Demo(89);
   }
}

출력

The Demo objects have been created.
The common constructor has been invoked
The default constructor has been invoked
The common constructor has been invoked
The parametrized constructor has been invoked

Demo라는 클래스에는 매개변수가 없는 생성자, 매개변수화된 생성자 및 기본 함수가 포함되어 있습니다. 메인 함수 내에서 Demo 클래스의 인스턴스가 생성되는데, 하나는 매개변수가 있고 다른 하나는 매개변수가 없습니다.