學(xué)習(xí)啦 > 知識(shí)大全 > 知識(shí)百科 > 百科知識(shí) > java什么是構(gòu)造函數(shù)

java什么是構(gòu)造函數(shù)

時(shí)間: 歐東艷656 分享

java什么是構(gòu)造函數(shù)

  構(gòu)造函數(shù) ,是一種特殊的方法。主要用來(lái)在創(chuàng)建對(duì)象時(shí)初始化對(duì)象, 即為對(duì)象成員變量賦初始值,總與new運(yùn)算符一起使用在創(chuàng)建對(duì)象的語(yǔ)句中。特別的一個(gè)類可以有多個(gè)構(gòu)造函數(shù) ,可根據(jù)其參數(shù)個(gè)數(shù)的不同或參數(shù)類型的不同來(lái)區(qū)分它們 即構(gòu)造函數(shù)的重載。

  Java 在創(chuàng)建對(duì)象的時(shí)候會(huì)要執(zhí)行它的構(gòu)造函數(shù)。不僅如此,Java 還要執(zhí)行父類的構(gòu)造函數(shù),往上一級(jí)一級(jí)直到?jīng)]有父類為止。對(duì)于初學(xué)者來(lái)說(shuō),有三個(gè)問(wèn)題不容易搞懂:

  1、父類的構(gòu)造函數(shù)是否一定會(huì)執(zhí)行?

  2、是先執(zhí)行子類的構(gòu)造函數(shù)還是先執(zhí)行父類的構(gòu)造函數(shù)?

  3、如果父類有多個(gè)構(gòu)造函數(shù),那么 Java 會(huì)選擇哪一個(gè)?

  - 父類的構(gòu)造函數(shù)是否一定會(huì)執(zhí)行?

  是的,父類的構(gòu)造函數(shù)一定會(huì)執(zhí)行。所以如果某個(gè)類的層次很深,那么它創(chuàng)建對(duì)象時(shí)就會(huì)要執(zhí)行一大堆的構(gòu)造函數(shù)。

  - 是先執(zhí)行子類的構(gòu)造函數(shù)還是先執(zhí)行父類的構(gòu)造函數(shù)?

  Java 會(huì)順著繼承結(jié)構(gòu)往上一直找到 Object,然后從 Object 開(kāi)始往下依次執(zhí)行構(gòu)造函數(shù)。先執(zhí)行父類的構(gòu)造函數(shù),那么子類的構(gòu)造函數(shù)執(zhí)行的時(shí)候就不需要擔(dān)心父類的成員是否初始化好了。

  - 如果父類有多個(gè)構(gòu)造函數(shù),那么 Java 會(huì)選擇哪一個(gè)?

  如果父類有多個(gè)構(gòu)造函數(shù),那么子類可以在構(gòu)造函數(shù)中選擇其中一個(gè)(且最多只能選擇一個(gè))來(lái)執(zhí)行。如果子類沒(méi)有選擇,那么 Java 將會(huì)執(zhí)行父類的缺省構(gòu)造函數(shù)。下面是一個(gè)例子:

  父類:

  public class SuperClass {

  public SuperClass() {

  System.out.println("super class constructed.");

  }

  public SuperClass(String name) {

  System.out.println("super class constructed with name: " + name);

  }

  }

  子類:

  public class SubClass extends SuperClass {

  public SubClass() {

  System.out.println("sub class constructed.");

  }

  public SubClass(String name) {

  super(name);

  System.out.println("sub class constructed with name: " + name);

  }

  public static void main(String[] args) {

  new SubClass();

  new SubClass("world");

  }

  }

  執(zhí)行結(jié)果:

  super class constructed.

  sub class constructed.

  super class constructed with name: world

  sub class constructed with name: world

  如果去除SubClass中的super(name)的話,輸出將是:

  super class constructed.

  sub class constructed.

  sub class constructed with name: world

  這說(shuō)明創(chuàng)建子類object時(shí)只有默認(rèn)constructed會(huì)向下執(zhí)行/初始化,其他constructed需要使用super關(guān)鍵字才可以實(shí)現(xiàn)

245767