如果我有构造函数
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的实例?
答案 0 :(得分:4)
我认为你的意思是:
public class StackOverflowQuestion
{
public StackOverflowQuestion(){ // constructor
//does code
}
public StackOverflowQuestion(int a){ // another constructor
this();
}
}
并称之为:
StackOverflowQuestion puzzled = new StackOverflowQuestion(4);
这只会创建一个对象,因为new
只执行一次。调用this()
将在不创建新对象的情况下执行其他构造函数中的代码。该构造函数中的代码能够修改当前创建的实例。
答案 1 :(得分:3)
它只创建一个实例。它的一个用例是给出构造函数参数的默认值:
public class StackOverflowQuestion
{
public StackOverflowQuestion(int a) {
/* initialize something using a */
}
public StackOverflowQuestion() {
this(10); // Default: a = 10
}
}
答案 2 :(得分:1)
constructor
不会创建对象。它只是初始化对象的状态。它是创建对象的new
运算符。仔细阅读Creation of New Class Instance - JLS。这意味着什么:
public class StackOverflowQuestion
{
public StackOverflowQuestion(){ // constructor
//does code
}
public StackOverflowQuestion(int a){ // another constructor
this();
}
}
StackOverflowQuestion puzzled = new StackOverflowQuestion(4);
StackOverflowQuestion
运算符创建new
的新对象,就在对新创建的对象的引用作为结果返回并分配给StackOverflowQuestion puzzled
引用变量之前,构造函数StackOverflowQuestion(int a)
调用this()
即public StackOverflowQuestion()
,默认构造函数内的代码(如果有)运行,控件返回`StackOverflowQuestion(int a)
,其余代码(如果有的话)处理内部以初始化新对象。
答案 3 :(得分:1)
this()
与new StackOverflowQuestion()
this(5)
与new StackOverflowQuestion(5)
this()
和this(5)
调用同一个类中的另一个构造函数。
因此在这个例子中:
public class StackOverflowQuestion
{
private int x;
private int y;
private int a;
public StackOverflowQuestion(){
this.x = 1;
this.y = 2;
}
public StackOverflowQuestion(int a){
this();
this.a = a;
}
}
对this()
的调用只会初始化对象而不会创建新实例。记得new StackOverflowQuestion(5)
已被调用已经调用构造函数,该构造函数实际创建了StackOverflowQuestion
对象的新实例
答案 4 :(得分:0)
在使用“new”运算符时创建类的实例。完全可以创建一个没有构造函数的类,因为在这种情况下,默认情况下,没有参数的构造函数可用。
“this”关键字只指向这个特定对象,所以调用“this()”意味着“调用我自己的构造函数,没有参数的那个并执行里面的内容”