【问题标题】:Calling 'this' from parameterized constructor - better way Java [closed]从参数化构造函数调用“this”-Java 的更好方法 [关闭]
【发布时间】:2017-05-26 18:43:34
【问题描述】:

考虑一个班级学生。以下是在默认构造函数中初始化实例值的两种方法:

class Student {
     int units;

     Student() {
         this(10);
     }

     Student(int x) {
         units = x;
     }
 };

上面比下面好:

 class Student {
     int units;

     Student() {
         units = 10;
     }

     Student(int x) {
         units = x;
     }
 };

哪种方式更好更可取?

【问题讨论】:

标签: java


【解决方案1】:

在这个简单的例子中,我们看不到一种或另一种解决方案的真正优势。

但作为一般规则,我更喜欢构造函数调用另一个构造函数的解决方案,因为它避免重复自己。
假设在构造函数中添加了两个或三个参数并执行了一些处理。您可能应该在没有参数的构造函数中复制它。

例如在构造函数中有重复:

class Student {
  int units;
  int otherUnits;
  boolean isTrue;

  Student() {
     this.units = 10;
     this.otherUnits = 20;
     this.isTrue = true; 
     computeIntermediaryValue(units,otherUnits,isTrue);
  }

  Student(int units, int otherUnits, boolean isTrue) {
     this.units = units;
     this.otherUnits = otherUnits;
     this.isTrue = isTrue;              
     computeIntermediaryValue(units,otherUnits,isTrue);         
  }
}

应避免不必要的重复。

在构造函数中没有重复看起来更好:

class Student {
  int units;
  int otherUnits;
  boolean isTrue;

  Student() {
     this(10, 20, true);
  }

  Student(int units, int otherUnits, boolean isTrue) {
     this.units = units;
     this.otherUnits = otherUnits;
     this.isTrue = isTrue;              
     computeIntermediaryValue(units,otherUnits,isTrue);         
  }
}

【讨论】:

  • “应避免不必要的重复。” 有趣的句子,特别是因为这个问题有重复。
  • 好词 :) 不幸的是,在您所指的内容中:stackoverflow.com/questions/581873/... 评估最多的答案带来了零解释,我在任何回复中都没有找到任何对代码重复的引用。除了在较旧的问题中,OP 不知道如何处理。 @Tom 不是这里的情况
【解决方案2】:

这是有争议的并且取决于风格。

就我个人而言,我会选择第一种方法,因此只有一个 primary 构造函数,所有数据最终都会通过该构造函数。其他的二级构造函数,你可以自己设置一些值(不注入),但所有的数据最终都是通过同一个构造函数注入的。

【讨论】:

    【解决方案3】:

    内存问题:从其他构造函数调用一个会在内存基础上花费您。因为它需要使用堆栈内存。为了提高内存效率,您应该使用第二种方法。

    速度问题: 在第二种方法中,编译器首先必须检查将调用哪个构造函数,然后确定它将调用所需的构造函数。但是编译器花费的时间在某些情况下会花费你,而在第一种方法中总是调用默认构造函数。

    用户问题: 最重要的是编写代码的方式以及调用不同参数的参数化构造函数的需要。用户需要在构造函数调用中放入自定义数据的情况,第二种方法似乎相当不错。

    虽然没有提到这方面的标准做法,但我喜欢使用第一种方法。(由用户决定)

    *@davidxxx 提到的重复问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多