Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khối khởi tạo (Initializer Block) trong Java


Khối khởi tạo dùng để khai báo phần chung của các constructor. Xem ví dụ:

Ví dụ

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);    } }

Kết quả

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

Lớp Demo chứa constructor không tham số, constructor có tham số và hàm main. Trong main, một thể hiện của lớp Demo được tạo, một có tham số, một không. Khối khởi tạo chạy trước mỗi constructor.