【17】java构造函数
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