1

这些来自 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;
}
4

3 回答 3

6

这些构造函数被重载以使用 调用另一个构造函数this(...)。第一个无参数构造函数使用空参数调用第二个。第二个调用第三个构造函数(未显示),它必须采用StockStringlong。这种称为构造函数链的模式通常用于提供多种实例化对象的方法,而无需重复代码。具有较少参数的构造函数用默认值填充缺少的参数,例如 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;
}

另请注意,调用后this(...)仍然可以执行,尽管这偏离了链接模式:

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

    anotherField = extraCalculation(stock);
}
于 2012-02-09T02:25:56.017 回答
1

这就是我们所说的伸缩模式。但是您在 Quote 类中使用的方式没有用。例如,认为在您的类中,您有一个必需属性和两个可选属性。在这种情况下,您需要提供具有该必需属性的构造函数,然后在该构造函数中,您需要使用可选参数的默认值调用其他构造函数。

// Telescoping constructor pattern - does not scale well!
public class NutritionFacts {
private final int servingSize; // (mL)  required
private final int servings; // (per container) required
private final int calories; //  optional
private final int fat; // (g) optional
private final int sodium; // (mg) optional
private final int carbohydrate; // (g)   optional
public NutritionFacts(int servingSize, int servings) {
this(servingSize, servings, 0);
}
public NutritionFacts(int servingSize, int servings,
int calories) {
this(servingSize, servings, calories, 0);
}
public NutritionFacts(int servingSize, int servings,
int calories, int fat) {
this(servingSize, servings, calories, fat, 0);
}

我从有效的 Java 版本 2 中提取了这个 Java 代码。

于 2012-02-09T03:12:31.180 回答
0

它正在调用一个接受整数参数的构造函数。

这是我在 Java 教程网页上找到的:

您可以使用 this 从实例方法或构造函数中引用当前对象的任何成员。

在这种情况下,它从 ArrayList 类中调用一些东西。这也在 Java 教程部分:

在构造函数中,您还可以使用 this 关键字调用同一类中的另一个构造函数。这样做称为显式构造函数调用。

所以你在这种情况下看到的是一个显式构造函数调用

来源:https ://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

于 2016-03-10T21:48:32.477 回答