從頭認識java-4.1 建立與初始化對象

來源:互聯網
上載者:User

從頭認識java-4.1 建立與初始化對象

這一章節我們來聊聊建立與初始化對象。

這個需要討論的問題源自於c語言,在c語言中,很大部分的錯誤是忘記了初始化某些東西,他把庫的構建的使用需要完成兩個操作-建立與初始化,但是在java裡面,使用構造器來建立與初始化,他們是在一起的,因此避免了一部分忘記初始化的錯誤。

 

package com.ray.testobject;public class Test {public static void main(String[] args) {TestClass t1=new TestClass();TestClass t2=new TestClass();}}class TestClass {public TestClass() {System.out.println(TestClass created);}public TestClass(int param) {System.out.println(TestClass created);System.out.println(param);}}

輸出:

 

TestClass created
TestClass created
1

從輸出結果我們可以看到,其實在建立對象的時候我們利用構造器已經進一步的進行初始化,而不需要特定的運行初始化函數。

如果構造器不傳入任何參數,那麼,就會建立一個沒有任何屬性的對象。

 

需要注意的是:即便我們沒有對對象初始化屬性,編譯器也會為我們初始化,這樣就可以減少一定的錯誤。

我們修改一下上面的代碼:

 

package com.ray.testobject;public class Test {public static void main(String[] args) {TestClass t1 = new TestClass();TestClass t2 = new TestClass(1);}}class TestClass {private String name;//增加屬性private int id;//增加屬性public TestClass() {System.out.println(TestClass created);System.out.println(id);System.out.println(name);}public TestClass(int param) {System.out.println(TestClass created);System.out.println(param);System.out.println(id);System.out.println(name);}}

 

 

輸出:

TestClass created
0
null
TestClass created
1
0
null
 

從輸出結果可以看見,對象在初始化的時候,已經把裡面的屬性初始化。

我們再來修改一下程式,然後看看構造器初始化的參數與對象初始化的參數兩者之間有什麼不同。

 

package com.ray.testobject;public class Test {public static void main(String[] args) {TestClass t1 = new TestClass();TestClass t2 = new TestClass(1);}}class TestClass {private String name;public TestClass() {System.out.println(TestClass created);System.out.println(name);}public TestClass(String param) {//修改了param 的類型System.out.println(TestClass created);System.out.println(param);System.out.println(name);}}

輸出:

 

TestClass created
null
TestClass created
1
null

因為如果需要使用具有param構造器來構造對象,必須初始化param,因此,param是認為的設定,而name這個屬性域,則是由編譯器自動初始化。

 

總結:這一章節討論了建立與初始化對象的一些話題。

 

聯繫我們

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