Pet*_*_ch 1 java spring constructor constructor-chaining
这些是来自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());
}
Run Code Online (Sandbox Code Playgroud)
反对这个
public class Bicycle {
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
Run Code Online (Sandbox Code Playgroud)
重载这些构造函数以使用调用另一个构造函数this(...).第一个无参数构造函数使用null参数调用第二个.第二呼叫的第三构造(未示出),其必须采取Stock,String和long.这种称为构造函数链接的模式通常用于提供多种实例化对象的方法,而无需重复代码.参数较少的构造函数使用默认值填充缺少的参数,例如with new Date().getTime(),或者只是传递nulls.
请注意,必须至少有一个不调用的构造函数,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;
}
Run Code Online (Sandbox Code Playgroud)
另请注意,调用this(...)仍然可以执行,但这与链接模式不同:
public Quote(Stock stock, String price) {
this(stock, price, new Date().getTime());
anotherField = extraCalculation(stock);
}
Run Code Online (Sandbox Code Playgroud)