Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

spring - what type of java constructors are these? Constructor chaining?

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

as oppossed to this one

public class Bicycle {

public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...