我有一个包含以下成员字段和构造函数的类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;
}
使用 this
关键字从另一个构造函数调用构造函数。 如果确实调用了另一个构造函数,则它必须是构造函数主体中的第一个语句。
public SomeClass(int someInt, String someStr, String strTwo) {
// Yes you can do this
this(someInt, someStr); // calling the former constructor
this.strTwo = strTwo;
}
您需要在第三个构造函数中使用关键字"this":
public SomeClass(int someInt, String someStr, String strTwo) {
// can i do this
this(someInt, someStr); // that is, calling the former constructor
this.strTwo = strTwo;
}
那么它应该有相同的结果,是的。
不,至少不是你怎么写的。
第三个构造函数创建new
对象,然后设置其this
对象strTwo
的成员变量。您在这里基本上是在处理两个单独的对象。您在第三个构造函数中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
}
如果您的目标是创建与双参数构造函数创建的对象在功能上相同的单个对象,则必须执行以下操作:
public SomeClass(int someInt, String someStr, String strTwo) {
this.SomeClass(someInt, someStr);
this.strTwo = strTwo;
}
这将等效于在一个函数中执行所有成员字段集的代码,对对象构造实际如何获得最终产品只有很小的变化。与往常一样,请注意,在这两个函数之间创建的对象将是相等的,但不是"相同"的对象:也就是说,它们将指向内存中保存相同值的不同位置。在谈论对象时,"相同"可能是一个棘手的词。