class other{
private static int x=0;
static{
System.out.println("other--靜態代碼塊");
}
other(){
System.out.println("other--構造函數"+(x++));
}
}
class superclass{
static{
System.out.println("父---靜態代碼塊");
}
{
System.out.println("父---構造代碼塊");
}
superclass(){
System.out.println("父----構造函數");
}
other o=new other();
}
class newload extends superclass{
static{
System.out.println("子---靜態代碼塊");
}
other o=new other();
{
System.out.println("子---構造代碼塊");
}
newload(){
System.out.println("子----構造函數");
}
public static void main(String[] args){
System.out.println("main方法");
new newload();
}
}
運行結果:
父—靜態代碼塊
子—靜態代碼塊
main方法
父—構造代碼塊
other–靜態代碼塊
other–構造函數0
父—-構造函數
other–構造函數1
子—構造代碼塊
子—-構造函數
PS:
(1)構造代碼塊和類的屬性類優先級相同,誰在前面誰先執行;
(2)靜態只執行一次,在類加載的時候;
說一點其他的:關於new的過程:
`Person p=new Person("zhangsan",20);`
該句話都做了什麼事情?
1,因爲new用到了Person.class,所以會先找到Person.class文件並加載到內存中;
2,執行該類中的static代碼塊,如果有的話,給Person.class類進行初始化;
3,在堆內存中開闢空間,分配內存地址;
4,在堆內存中建立對象的持有屬性,並進行默認初始化;
5,對屬性進行顯式初始化;
6,對對象進行構造代碼塊初始化;
7,對對象進行與之對應的構造函數初始化;
8,將內存空間地址賦給棧內存中的p變量。