Java中,所有對象都是創建出來的,對象的自動初始化過程,是由類的構造函數完成的。當程序員沒有提供一個默認的構造函數時,編譯器會生成一個默認的構造
函數,用於創建一個空對象。但是當程序員提供了一個或多個構造函數后,編譯器就不會再生成默認的構造函數。
所以,假如程序員提供了一個有參數的構造函數,而在創建該類的對象時,直接采用new obj的方式,即未提供任何參數,則編譯器會提示找不到相應的構造函數。
一句話總結:有,就只能用你的,沒有,哥幫你生成一個空的。
1 public class Flower {
2
3 private int petalCount = 0;
4 private String fnameString = new String("null");
5 /**
6 *
7 */
8 public Flower(int i) {
9 petalCount = i;
10
11 System.out.println("Constructed only by petal:" + petalCount);
12 }
13
14 public Flower(String name){
15 fnameString = name;
16
17 System.out.println("Constructed only by name:" + fnameString);
18 }
19
20 public Flower(String name,int petal){
21 this(name);
22 //this(petal); //not allowed
23 this.petalCount = petal;
24
25 System.out.println("Constructed both by name:" + name + " and petal:"+ petal);
26 }
27
28 public Flower(){
29 this("Rose",27);
30
31 System.out.println("Constructed without parameters");
32 }
33 }
構造函數也可以調用構造函數,只是第22行值得注意。
1 Flower fa = new Flower();
2
3 Flower fb = new Flower(36);
4
5 Flower fc = new Flower("Baihe");
Constructed only by name:Rose
Constructed both by name:Rose and petal:27
Constructed without parameters
Constructed only by petal:36
Constructed only by name:Baihe