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

ขั้นตอนการอ่าน Static Members ใน Java Class

Static variable ถูกสร้างที่เวลา class loading แม้ก่อนการ execute static block และวัตถุประสงค์ของ static block คือการกำหนดค่าให้ static variables Static variable เก็บค่าที่ shared ระหว่างทุก instances ของคลาสที่มันถูกกำหนด และ static block เป็นส่วนของโค้ดที่ execute เมื่อ class ถูกโหลดครั้งแรก หากเราต้องการ logic ใดๆ ที่ต้อง execute ที่เวลา class loading logic นั้นต้องวางใน static block เพื่อให้ execute ที่เวลา class loading

JVM ทำตามขั้นตอนด้านล่างเพื่ออ่าน static members ในคลาส:

  • Identification of static members from top to bottom (ระบุ static members จากบนลงล่าง)
  • Execution of static variables assignment and static blocks from top to bottom (execute การกำหนดค่า static variables และ static blocks จากบนลงล่าง)
  • Execution of the main method (execute main method)

ตัวอย่าง

public class StaticFlow {
    static int firstNumber = 10;
    static {
        firstMethod();
        System.out.println("first static block");
    }
    public static void main(String[] args) {
        firstMethod();
        System.out.println("main method executed");
    }
    public static void firstMethod() {
        System.out.println(secondNumber);
    }
    static {
        System.out.println("second static block");
    }
    static int secondNumber = 20;
}

ผลลัพธ์

0
first static block
second static block
20
main method executed