簡體   English   中英

這些是什么類型的Java構造函數? 構造函數鏈接?

[英]what type of java constructors are these? 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());
    }

與此相反

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);
}

這就是我們所說的伸縮模式。 但是您在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代碼。

它正在調用采用整數參數的構造函數。

這是我在Java教程網頁上找到的:

您可以使用此方法從實例方法或構造函數中引用當前對象的任何成員。

在這種情況下,它正在從ArrayList類中調用某些東西。 這也在Java Tutorials部分中:

在構造函數中,您還可以使用this關鍵字在同一類中調用另一個構造函數。 這樣做稱為顯式構造函數調用。

因此,在這種情況下,您看到的是顯式構造函數調用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM