Java static 靜態代碼塊、代碼塊


簡述

  • static{} 靜態代碼塊,加載類之前執行
  • {} 代碼塊,每次new的時候都會被執行

示例

類:


public class Student {
    int age;
    String name;
    boolean sex;
    public Student(){
        age=10;
        name="Xu";
        sex=false;
    }
    static{
        System.out.println("This is a static block");
    }
    {
        System.out.println("這是一個代碼塊");
    }
}

調用函數:

public class Student_test {

    public static void main(String[] args) {
        Student student1= new Student();
        Student student2= new Student();
        Student student3= new Student();
        Student student4= new Student();
        
    }
}

輸出結果:

This is a static block
這是一個代碼塊
這是一個代碼塊
這是一個代碼塊
這是一個代碼塊

創建了4個對象,但是static塊只執行一次,而代碼塊,每次創建對象,都會被執行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM