類載入與對象初始化

來源:互聯網
上載者:User

標籤:strong   檔案   os   代碼   工作   時間   

1. 初始化原因:避免發生空指向異常。

2. 類載入與初始化的順序:

    2.1 類載入時間:

         每個類的編譯代碼都存在於他自己的獨立檔案中,該檔案的載入通常發生在建立類的第一個對象時,或是訪問類的static域或static方法時。

    2.2 初始化順序:(先父類後子類,建立對象之前先對類中的域進行初始化)

       首先,類載入器主動載入主類(主類的初始化順序與下面普通類一樣),找到main方法,在main方法中根據第一行要建立的對象,載入該類的位元組碼檔案,如果編譯器注意到她有基類(這是由extends關鍵字得知)則繼續載入(,不管是否需要建立基類對象,這都要發生。)在根基類中首先的static初始化,static代碼塊,依次是子類,至此類載入和靜態初始化及靜態代碼快的執行已經完畢,對象就可以被建立。首先對象中所有的域都會設為預設值,然後在調用父類的構造方法之前普通域會被初始化,依次執行直到完成初始化工作。

3. 代碼驗證:

    class Person{
 private static String city = "shanxi" ;
 private String name = new String("wh") ;
 private String age ;
 static{
  System.out.println(city+"perosn靜態代碼塊");
 }
 {
  System.out.println(name+"普通塊"+age);
 }
 public Person(String name,String age){
  System.out.println(city+"---------->"+this.name+"----------->"+this.age);
  this.name = name ;
  this.age  = age ;
  System.out.println(city+"---------->"+this.name+"----------->"+this.age);
 }
}
class Student extends Person{
 private static String school = "xd" ;
 private String sname = new String("sn") ;
 private String sage ;
 static{
  System.out.println(school+"   student靜態代碼塊");
 }
 {
  System.out.println(sname+"   student普通塊"+sage);
 }
 public Student(String name,String age){
  super(name,age) ;
  System.out.println(Student.school+"------------>"+this.sname+"------->"+this.sage);
  this.sname = name ;
  this.sage = age ;
  System.out.println(Student.school+"------------>"+this.sname+"------->"+this.sage);
 }
}
public class InitSort {
 public static void main(String[] args) {
  Student s1 = new Student("cjt","23") ;
  Student s2 = new Student("cjr","21") ;
 }
}

輸出:

shanxiperosn靜態代碼塊
xd   student靜態代碼塊
wh普通塊null
shanxi---------->wh----------->null
shanxi---------->cjt----------->23
sn   student普通塊null
xd------------>sn------->null
xd------------>cjt------->23
wh普通塊null
shanxi---------->wh----------->null
shanxi---------->cjr----------->21
sn   student普通塊null
xd------------>sn------->null
xd------------>cjr------->21

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.