6

我已经开始使用 setter 而不是将参数放入默认构造函数中,因为它可以帮助我更好地组织代码

问题是我正在做的项目中唯一的变量是一个字符串,我不确定是否应该在声明中初始化它(作为全局变量?),在 setter 实例方法中还是是否在类构造函数。

我想知道这个设置是否存在任何问题,是否在使用它的设置器之前实例没有初始化:

class MyClass{

  private String myString; 

  public MyClass(){

  }
  public void setStuff(String s){ 

    this.myString=s;
  }
}
4

5 回答 5

7

为什么不直接初始化为:

private String myString = "My string";

可能的最简单的方法。

于 2012-09-26T19:12:58.360 回答
3

好吧,这实际上取决于该变量是什么以及它将做什么。

它是一个常数吗?如果是这样,您可以像这样初始化它:

private final String myString = "foo";

Is it meant to be an instance variable? If so, you should go for something like this:

public MyClass(string myString)
{
    this.myString = myString;
}

If it's some kind of optional property, the way you have now might be fine as well. In the end, it really all depends on what you're going to be doing with that variable.

于 2012-09-26T19:14:53.837 回答
2

Not sure what you mean by global variable? Is it truely a variable that is the same inrespective of the object that is created? If so it should be static

private static String myString = "str";

If it never changes then it should be final and is then a global constant

public static final String MY_STRING = "str";

This can then be public and accessed via

MyClass.MY_STRING

If it is only applicable for each object of the class that is created then either initialise it in the constructor or in the declaration

于 2012-09-26T19:14:54.627 回答
1

Just like you have it looks good to me. BTW, "global varible" can be misleading cause it may imply that the var is public whereas it is private but accessible outside via a public getter/setter.

But to initialize a String, the simplest way is:

private String foo = "some string";
于 2012-09-26T19:15:29.480 回答
0

It really depends on what MyClass will be doing. Most of the time, it's best to have a constructor that will initialize private variable and to also have a getter and setter for it.

One reason is what if MyClass has a method foo which needs myString to be initialized and you forgot to call setStuff?

于 2012-09-26T19:14:58.463 回答