public class Test03 { public static void main(String[] args) { { int x = 10; //局部代碼塊 限定變量的生命週期 System.out.println(x); } Student s1 = new Student(); System.out.println("-----------"); Student s2 = new Student("zhangsan",23); } static {//優先主方法執行 System.out.println("主方法類中的靜態代碼塊"); } } class Student { private String name; private int age; public Student() { //空參構造 System.out.println("kongca"); } public Student(String name, int age) { //有參構造 this.name = name; this.age =age; System.out.println("youcan"); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public int getage() { return age; } {//構造代碼塊:每創一次對象就執行一次,並且優先於構造函數執行 //System.out.println("代碼塊"); study(); } public void study() { System.out.println("xuexi"); } static {//隨類的加載而加載,且只執行一次,同來給類進行初始化 System.out.println("靜態代碼塊"); } }