有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

递归在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的实例吗


共 (5) 个答案

  1. # 1 楼答案

    类的实例是在使用“new”操作符时创建的。创建一个没有构造函数的类是完全可能的,因为在这种情况下,默认情况下,没有参数的构造函数是可用的

    “this”关键字只指向这个特定的对象,所以调用“this()”意味着“调用我自己的构造函数,一个没有参数的构造函数,并执行其中的内容”

  2. # 2 楼答案

    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对象的一个新实例

  3. # 3 楼答案

    它只创建一个实例。它的一个用例是为构造函数参数提供默认值:

    public class StackOverflowQuestion
    {
        public StackOverflowQuestion(int a) {
            /* initialize something using a */
        }
    
        public StackOverflowQuestion() {
            this(10); // Default: a = 10
        }
    }
    
  4. # 4 楼答案

    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),内部为初始化新对象而处理的剩余代码(如果有)

  5. # 5 楼答案

    我想你的意思是:

    public class StackOverflowQuestion
    {
    
        public StackOverflowQuestion(){ // constructor
           //does code
        }
    
        public StackOverflowQuestion(int a){ // another constructor
           this();
        }
    }
    

    可以这样说:

    StackOverflowQuestion puzzled = new StackOverflowQuestion(4);
    

    这将只创建一个对象,因为new只执行一次。调用this()将在另一个构造函数中执行代码,而不创建新对象。该构造函数中的代码可以修改当前创建的实例