什么类型的java构造函数是这些?构造函数链接? [英] what type of java constructors are these? Constructor chaining?

查看:172
本文介绍了什么类型的java构造函数是这些?构造函数链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是来自github上的spring amqp示例
https:// github.com/SpringSource/spring-amqp-samples.git
什么类型的java构造函数是这些?

These are from the spring amqp samples on github at https://github.com/SpringSource/spring-amqp-samples.git what type of java constructors are these? are they a short hand for getters and setters?

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(...)的构造函数。第一个无参数构造函数调用第二个带有空参数。第二个调用第三个构造函数(未示出),它必须带有库存 String long 。此模式称为构造函数链接,通常用于提供实例化对象的多种方法,而不使用重复代码。参数较少的构造函数使用默认值填充缺少的参数,例如使用 new Date()。getTime(),否则只传递 null

These constructors are overloaded to call another constructor using this(...). The first no-arg constructor calls the second with null arguments. The second calls a third constructor (not shown), which must take a Stock, String, and long. This pattern, called constructor chaining, is often used to provide multiple ways of instantiating an object without duplicate code. The constructor with fewer arguments fills in the missing arguments with default values, such as with new Date().getTime(), or else just passes nulls.

请注意,必须至少有一个构造函数不会调用 this(...),而是提供对 super(...)的调用,后跟构造函数实现。当在构造函数的第一行上指定 this(...) super(...) ,则隐含了 super()的非arg调用。

Note that there must be at least one constructor that does not call this(...), and instead provides a call to super(...) followed by the constructor implementation. When neither this(...) nor super(...) are specified on the first line of a constructor, a no-arg call to super() is implied.

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

So assuming there isn't more constructor chaining in the Quote class, the third constructor probably looks like this:

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 )仍然可以执行,虽然这偏离了链式模式:

Also note that calls to this(...) can still be followed by implementation, though this deviates from the chaining pattern:

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

    anotherField = extraCalculation(stock);
}

这篇关于什么类型的java构造函数是这些?构造函数链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆