这些是什么类型的Java构造函数?构造函数链接?


问题内容

这些来自github上的spring amqp示例,位于https://github.com/SpringSource/spring-amqp-
samples.git
这些是
什么类型的Java构造函数?它们是吸气剂和吸气剂的捷径吗?

public class Quote {

    public Quote() {
        this(null, null);
    }

    public Quote(Stock stock, String price) {
        this(stock, price, new Date().getTime());
    }

与此相反

public class Bicycle {

public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}

问题答案:

这些构造函数被重载以使用调用另一个构造函数this(...)。第一个无参数构造函数使用空参数调用第二个。第二呼叫的第三构造(未示出),其必须采取StockStringlong。这种模式称为
构造函数链接 ,通常用于提供多种方法来实例化对象而无需重复代码。参数较少的构造函数使用默认值(例如with)填充缺少的参数new Date().getTime(),否则仅传递nulls。

请注意, 必须
至少有一个不调用的构造函数,this(...)而是提供对的调用,并在super(...)其后进行构造函数实现。如果在构造函数的第一行中均未指定this(...)super(...)super()则暗示对no-
arg的调用。

因此,假设类中没有更多的构造函数链接Quote,则第三个构造函数可能如下所示:

public Quote(Stock stock, String price, long timeInMillis) {
    //implied call to super() - the default constructor of the Object class

    //constructor implementation
    this.stock = stock;
    this.price = price;
    this.timeInMillis = timeInMillis;
}

还要注意,this(...)仍然可以在实现之后跟随to的调用,尽管这与链接模式有所不同:

public Quote(Stock stock, String price) {
    this(stock, price, new Date().getTime());

    anotherField = extraCalculation(stock);
}