java 構造方法

來源:互聯網
上載者:User

標籤:ack   不能   this   set   bsp   pack   int   其他   類的建構函式   

1、構造方法的格式是什嗎?有哪些注意事項?

修飾符   類名 (參數列表){}

構造方法沒有具體的傳回值,物件建構完方法就結束,構造方法的名字必須和類名保持一致。

如果沒有指定構造方法,預設是有一個空參數的構造方法

一個類可以寫多個構造方法,方法可以被重載,可以被private修飾,但是其他程式 不能建立對象

 1 package lianxi; 2  3 public class Person { 4     private String name;   //定義2個私人的屬性 5     private int age; 6     public Person(String name, int age){  //建立一個構造方法 7         this.name =name;     //需要this來調用構造方法 8         this.age =age; 9     }10     public String getName(){11         return name;12     }13     public void setName(String name){14         this.name =name;15     }16     public int getAge() {17         return age;18     }19     public void setAge(int age) {20         this.age = age;21     }22 }

this關鍵字

this.屬性 是代表本類

this(函數列表),是代表用哪一個方法,調用本類的建構函式

this使用必須要放在第一位,跟super衝突,不要一起使用

super關鍵字

調用父類的無參數建構函式

super();

調用父類的有參數建構函式

super(參數列表);

super預設也是給一個,要放在第一位

 

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.