5.4.1在构造函数中调用构造函数

我们可以在自定义类中的构造函数中调用构造函数,但是有一定的规则。

先看如下例子:

public class Flower {
    int petalCount = 0;
    String s = "initial value.";
    
    Flower(int petals) {
        petalCount = petals;
        System.out.println("Constructor w/ int arg only, petalCount = " + petalCount);
    }
    
    Flower(String ss) {
        s = ss;
        System.out.println("Constructor w/ String arg only, s = " + s);
    }
    
    Flower(String ss, int petals) {
        this(ss);
        //s = ss;
        //this(petals);  Can't call two.
        petalCount = petals;
        System.out.println("String & int args");
        
    }
    
    Flower() {
        this("hi", 24);
        System.out.println("Default Constructor.");
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Flower f = new Flower();
        System.out.println(f.s);
        System.out.println(f.petalCount);
    }
}

output:

Constructor w/ String arg only, s = hi
String & int args
Default Constructor.
hi
24

还记得我之前写的,在C++语言中构造函数调用构造函数。在这一方面,C++和Java是截然不同的。以后利用的时候千万不要搅浑了。

总结:

1. 尽管可以用this()调用一个构造函数,但却不能调用两个。此外,必须将构造函数调用置于最起始处,否则编译会报错。

2. 除了可以在构造函数中调用构造函数以外, 编译器禁止在其他方法中调用构造函数。

原文地址:https://www.cnblogs.com/wiessharling/p/3334915.html