----------------------------------天道酬勤
1.構造代碼塊
{
//構造代碼塊,用於初始化
}
2.靜態代碼塊
static{
//靜態代碼塊
}
隨着類的加載而加載,生命週期爲類的生命週期。
代碼如下:
class Person
{
Person()
{
System.out.println("父類構造函數運行中");
}
}
public class Student extends Person
{
private String id;
private String name;
private int age;
//構造代碼塊
{
System.out.println("構造代碼塊運行中...");
}
//靜態代碼塊
static{
System.out.println("靜態代碼塊運行中");
}
//構造函數
Student(String id,String name,int age)
{
System.out.println("帶參構造函數運行中...");
this.id=id;
this.name=name;
this.age=age;
}
Student()
{
System.out.println("空參構造函數運行中...");
}
public String toString()
{
return "學號:"+this.id+"姓名:"+this.name+"年齡:"+this.age;
}
}
class ConstructorDemo
{
public static void main(String[] args)
{
Student s=new Student("2019111","小喬",26);
System.out.println(s);
}
}
運行結果如下:
執行順序:
1.默認初始化,靜態代碼塊
2.進入構造函數
3.super,執行父類的構造函數
4.顯示初始化
5.構造代碼塊
6.構造函數體