【问题标题】:A constructor containing another constructor of the same Class/Object包含相同类/对象的另一个构造函数的构造函数
【发布时间】:2015-04-27 17:15:54
【问题描述】:

我有一个类 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(...) 关键字调用另一个构造函数
  • 'self.someInt' 是什么意思?我想应该是“this.someInt”

标签: java multiple-constructors


【解决方案1】:

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

public SomeClass(int someInt, String someStr, String strTwo) {
    // Yes you can do this
    this(someInt, someStr); // calling the former constructor
    this.strTwo = strTwo;
}

【讨论】:

    【解决方案2】:

    您需要在第三个构造函数中使用关键字“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;
    

    }

    那么它应该有相同的结果,是的。

    【讨论】:

      【解决方案3】:

      不,至少不是你写的那样。

      您的第三个构造函数创建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
      }
      

      如果您的目标是创建一个与由双参数构造函数创建的对象在功能上相同的单个对象,则必须这样做:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-12
        • 2012-06-22
        • 1970-01-01
        • 2014-08-01
        • 2018-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多