iT邦幫忙

DAY 22
1

初學Java系列 第 19

Day22.constructor與this()

constructor & this()
[constructor的優先順序]
一定是superclass的constructor先被建造完成後才會輪到其subclass的
->因為subclass的object可能會用到從superclass繼承下的東西,所以superclass的東西一定要先建立好,也可以把superclass想像成是subclass的父母,這樣就不會混淆

[有參數的superclass constructor]
若要呼叫有參數的superclass constructor的話,需要使用super(),並在誇號內置入所要傳入的參數,ex.

public class Human{
  private int weight;
  public Human(int theWeight){
    weight = theWeight;
  }
}
public class Yap extends Human{
  public Yap(int weight){
    super(weight);    //傳給Human去執行他的constructor
  }
}

[super()]
->從某個constructor呼叫同一個class另外一個constructor

->當某個override版本只有不能處理不同參數外,其他要做的事情都一樣時,就可以把程式碼只擺在一個constructor中,再使用this()去做不同部分即可

->每個constructor都可以呼叫this()或super(),但不能共存!

->this()只用在constructor中,且一定要是第一句指令


上一篇
Day21.constructor與superclass(續)
下一篇
Day23.life與scope
系列文
初學Java20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言