Java将类设置变量设置为默认值

时间:2014-04-30 12:38:25

标签: java

在Java中,如果我有一个类,如:

public class Example {

  private String s;
  private int i;

  public Example() {
  }

  // set variables back to default initializations
  public clear() {

     // how?
  }


}

当这个类被实例化时,我的理解是si将分别设置为null0

有没有办法定义一个clear方法,以便将所有类变量设置回默认值?

我意识到依靠默认值可能不是最佳做法,但我有数百个这样的变量(所有字符串和整数)的代码。当默认值恰好是我需要的时候,定义清晰的方法和初始化似乎是多余的。

4 个答案:

答案 0 :(得分:2)

由于您知道默认值是什么,因此您只需手动分配它。

int为0,对象为null,依此类推..(有关详细信息,请参阅JLS - 4.12.5. Initial Values of Variables

但问题是,为什么要这样做而不是简单地创建新实例?

答案 1 :(得分:1)

不要创建一个清晰的方法,只需重新实例化该类:

Example example = new Example();
example.doSomething();
example = new Example(); //this will reset the variable's values to their default

答案 2 :(得分:0)

Example example = new Example();
example.doSomeWork();
example = new Example(); //??

答案 3 :(得分:0)

如下所示:

public class Example {

  private String s;
  private int i;

  public Example() {
     this.clear();
  }

  // set variables back to default initializations
  public clear() {
     // call this method from within constructor and whenever you would like to reset
     s = new String("abc"); // example initializer, actually re-assignment
     i = 0; // presuming this is the default initilization
  }
}
相关问题