Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

บล็อกตัวเริ่มต้นอินสแตนซ์ใน Java

บล็อกตัวเริ่มต้นอินสแตนซ์ (Instance initializer block) ใช้สำหรับเริ่มต้นคุณสมบัติของออบเจ็กต์ มันถูกเรียกก่อนที่คอนสตรัคเตอร์จะถูกเรียก มันถูกเรียกทุกครั้งที่มีการสร้างออบเจ็กต์ ดูตัวอย่างด้านล่าง:

ตัวอย่าง

public class Tester {    {       System.out.println("Inside instance initializer block");    }    Tester(){       System.out.println("Inside constructor");    }    public static void main(String[] arguments) {       Tester test = new Tester();       Tester test1 = new Tester();    } }

ผลลัพธ์

Inside instance initializer block Inside constructor Inside instance initializer block Inside constructor