Java 構造方法

來源:互聯網
上載者:User

標籤:建構函式   為什麼   初始化   定義   sys   預設建構函式   選擇   使用   code   

構造方法

1.使用 new + 構造方法建立一個新對象

2.構造方法是定義在Java類中的一個用來初始化對象的方法

 構造方法沒有傳回值

構造方法的語句格式

 

 無參構造方法的使用
public class test6 {    public static void main(String[] args) {                Car c1 = new Car();    }}class Car{        public Car() {        // TODO Auto-generated constructor stub        System.out.println("無參數的構造方法~~~");    }}

運行結果:

無參數的構造方法~~~

運行結果說明,在執行個體化一個對象時,其實是調用了構造方法。

有參的構造方法

為什麼會有有參的構造方法呢?

其實目的只有一個,就是為了初始化成員變數的值。

class Car{    int tread;    int seat;        public Car() {        System.out.println("無參數的構造方法~~~");    }        public Car(int newTread, int newSeat){        tread = newTread;        seat = newSeat;        System.out.println("輪胎:"+tread+"  座椅:"+seat+"   有參數的構造方法~~~");    }}public class test6 {    public static void main(String[] args) {        Car c1 = new Car(4, 7); // 調用有參建構函式        Car c2 = new Car();     // 調用無參建構函式    }}

運行結果:

輪胎:4  座椅:7   有參數的構造方法~~~無參數的構造方法~~~
構造方法的重載

方法名相同,但參數不同的多個方法,調用時會自動根據不同的參數選擇相應的方法。

class Car{    int tread;    int seat;        public Car(int newTread) {        tread = newTread;        System.out.println("輪胎:"+tread+"無參數的構造方法~~~");    }        public Car(int newTread, int newSeat){        tread = newTread;        seat = newSeat;        System.out.println("輪胎:"+tread+"  座椅:"+seat+"   有參數的構造方法~~~");    }}public class test6 {    public static void main(String[] args) {        Car c1 = new Car(4, 7); // 調用第二參建構函式    }}

運行結果:

輪胎:4  座椅:7   有參數的構造方法~~~

運行結果表明,程式會跟根據執行個體化對象時傳入的參數的個數選擇調用哪個構造方法。

構造方法給對象賦值

構造方法不但可以給對象的屬性賦值,還可以保證給對象賦一個合理的值

class Car{    int tread;    int seat;        public Car(int newTread, int newSeat){        if(tread<4)    {    // 汽車都有4個輪子,如果傳入3個輪子就會自動改成4個輪子            tread = 4;            System.out.println("輸入有誤!自動校正為4");        }        else            tread = newTread;        seat = newSeat;        System.out.println("輪胎:"+tread+"  座椅:"+seat+"   有參數的構造方法~~~");    }}public class test6 {    public static void main(String[] args) {        Car c1 = new Car(3, 7); // 調用第二參建構函式    }}

運行結果:

輸入有誤!自動校正為4輪胎:4  座椅:7   有參數的構造方法~~~
注意:

1.有參建構函式和無參建構函式是可以共存的。

2.調用有參建構函式還是無參建構函式是看執行個體化對象時有沒有傳入參數,傳入多少個參數,系統自動選擇。

3.有建構函式時調用建構函式,沒有時調用系統給的預設建構函式。

4.當沒有指定構造方法時,系統會自動添加無參構造方法。

5.當有指定構造方法,無論是有參、無參的構造方法,都不會自動添加無參的構造方法。

 

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.