包含同一Class / Object的另一个构造函数的构造函数

时间:2015-04-27 17:15:55

标签: java multiple-constructors

我正在使用以下成员字段和构造函数

的类SomeClass
private int someInt;
private String someStr;
private String strTwo;

//the contructors
public SomeClass() {}

// second constructor
public SomeClass(int someInt, String someStr) {
    this.someInt = someInt;
    this.someStr = someStr;
}

// my emphasis here
public SomeClass(int someInt, String someStr, String strTwo) {
    // can i do this
    new SomeClass(someInt, someStr); // that is, calling the former constructor
    this.strTwo = strTwo;
}

第三个构造函数是否会创建相同的对象:

public SomeClass(int someInt, String someStr, String strTwo) {
    this.someInt = someInt;
    this.someStr = someStr;
    this.strTwo = strTwo;
}

3 个答案:

答案 0 :(得分:4)

使用lastuploadedtime关键字call a constructor from another constructor。如果你确实调用了另一个构造函数,那么它必须是构造函数体中的第一个语句。

this

答案 1 :(得分:2)

不,至少不是你怎么写的。

您的第三个构造函数创建$db = null;对象,然后设置其new对象的strTwo成员变量。你基本上是在处理两个独立的对象。第三个构造函数中的this对象将被垃圾收集,因为在离开构造函数后没有对它的引用。

new

如果您的目标是创建一个功能与双参数构造函数创建的对象相同的单个对象,则必须执行以下操作:

//This function is called when creating a new object with three params
public SomeClass(int someInt, String someStr, String strTwo) {
    new SomeClass(someInt, someStr); //Here you create a second new object
    //Note that the second object is not set to a variable name, so it is
    //immediately available for garbage collection
    this.strTwo = strTwo; //sets strTwo on the first object
}

这将是在一个函数中执行所有成员字段集的等效代码,对象构造实际上如何到达最终产品只有很小的变化。与往常一样,请注意在这两个函数之间创建的对象将是相同的但不是“相同”对象:即它们将指向内存中具有相同值的不同位置。在谈论对象时,“相同”可能是一个棘手的词。

答案 2 :(得分:2)

您需要在第三个构造函数中使用关键字“this”:

https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=API_KEY

}

然后它应该有相同的结果,是的。