gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:16:27 25 4
gpt4 key购买 nike

这些来自 github 上的 spring amqp 示例 https://github.com/SpringSource/spring-amqp-samples.git这些是什么类型的java构造函数?它们是 getter 和 setter 的简写吗?

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。这种称为构造函数链的模式通常用于提供多种方法来实例化一个对象而无需重复代码。参数较少的构造函数用默认值填充缺少的参数,例如使用 new Date().getTime(),或者只是传递 null

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

假设 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(...) 后仍然可以执行,尽管这偏离了链接模式:

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

anotherField = extraCalculation(stock);
}

关于java - 这些是什么类型的java构造函数?构造函数链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9204560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com