java中有關初始化的問題

來源:互聯網
上載者:User

標籤:問題   class   順序   變數定義   一個   private   print   靜態   決定   

在類的內部,變數定義的先後順序決定了初始化順序,即時變數定義分散在方法定義之外,它們依舊會在任何方法(包括構造器)被調用之前得到初始化

其中初始化的順序先是靜態對象,其後是非靜態對象

例如:

class Cat{    private Dog dog1=new Dog(1);    static private Dog dog2=new Dog(2);    public Cat(int n){        System.out.println("第"+n+"只貓");    }}class Dog{    public Dog(int n){        System.out.println("Dog("+n+")");    }}public class TestStatic {    public static void main(String[] args) {        System.out.println("test...");        Cat cat=new Cat(1);    }}  

運行結果:

test...Dog(2)Dog(1)第1隻貓

  

cat類和dog類構造器中列印資訊為了看初始化資訊

在main方法中,建立了一個Cat類,除構造方法外,有兩個對象,一個是靜態dog,另外一個是dog,因為靜態對象有先初始化,所以先列印出Dog(2),其後才是Dog(1)

最後才調用cat的構造方法,列印出cat(1)

 

非靜態執行個體初始化

{}裡初始化的內容在構造器之前執行,且每次產生該類{}將會重新被初始化

 

java中有關初始化的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.