Java中建立對象初始化過程的理解

來源:互聯網
上載者:User

標籤:屬性   car   this   double   聲明   bsp   rom   man   ati   

以下面程式為例:

1.源碼Cars.java通過編譯產生Cars.class檔案;

2.執行時分為兩步:

第一步將Cars類的位元組碼載入到記憶體中,

第二步是new之後自動執行的。①將屬性color和price初始化記憶體堆,並附上初始值null和0.0(聲明,賦初值);②調用有兩個參數的構造方法public Cars(String color,double price),把具體值"black"和60000賦值給形式參數color和price(即執行Cars("black",60000);)③在棧中建立一個變數car1,用來引用堆中對象的具體屬性("black"和60000),car1的值是一個16進位的數,表示一個虛地址;④重複①-③過程建立對象car2,car2與car1是不同的引用,指向不同的具體對象。也就是說,car1和car2分別引用不同的具體內容。

 

public class Cars {

private String color;

private double price;

     public Cars(String color,double price){

this.color = color;

this.price = price;

}

public void setColor(String color) {

this.color = color;

}

public void setPrice(double price) {

this.price = price;

}

public static void main(String[] args) {

       Cars car 1= new Cars("black",60000);

          Cars car 2= new Cars(“red",50000);

}

}

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.