递归在Java中使用this()是否会创建更多对象的递归实例?
如果我有一个构造函数
public class Sample {
public static StackOverflowQuestion puzzled;
public static void main(String[] args) {
puzzled = new StackOverflowQuestion(4);
}
}
在我的一个程序的主要方法中
public class StackOverflowQuestion {
public StackOverflowQuestion(){
//does code
}
public StackOverflowQuestion(int a){
this();
}
}
这是通过构造函数2创建StackOverflowQuestion的实例,然后通过构造函数1创建StackOverflowQuestion的另一个实例,因此我现在有两个StackOverflowQuestion实例直接在彼此内部
或者构造函数2在这种情况下是横向调整,然后通过构造函数1创建StackOverflowQuestion的实例吗
# 1 楼答案
类的实例是在使用“new”操作符时创建的。创建一个没有构造函数的类是完全可能的,因为在这种情况下,默认情况下,没有参数的构造函数是可用的
“this”关键字只指向这个特定的对象,所以调用“this()”意味着“调用我自己的构造函数,一个没有参数的构造函数,并执行其中的内容”
# 2 楼答案
this()
与new StackOverflowQuestion()
不同this(5)
与new StackOverflowQuestion(5)
不同this()
和this(5)
调用同一类中的另一个构造函数因此,在本例中:
对
this()
的调用只会初始化对象,而不会创建新实例。记住new StackOverflowQuestion(5)
已经被调用,调用的构造函数实际上创建了StackOverflowQuestion
对象的一个新实例# 3 楼答案
它只创建一个实例。它的一个用例是为构造函数参数提供默认值:
# 4 楼答案
constructor
不会创建对象。它只是初始化对象的状态。创建对象的是new
操作符。通读Creation of New Class Instance - JLS。这意味着什么:一个新的
StackOverflowQuestion
对象是由new
操作符创建的,就在对新创建的对象的引用作为结果返回并分配给StackOverflowQuestion puzzled
引用变量之前,构造函数StackOverflowQuestion(int a)
调用this()
,即public StackOverflowQuestion()
,默认构造函数内的代码(如果有)运行,控件返回`StackOverflowQuestion(int a)
,内部为初始化新对象而处理的剩余代码(如果有)# 5 楼答案
我想你的意思是:
可以这样说:
这将只创建一个对象,因为
new
只执行一次。调用this()
将在另一个构造函数中执行代码,而不创建新对象。该构造函数中的代码可以修改当前创建的实例