开发者

Traditional Practice to initialize the field members of a class

I come from C++ background, where the field of a class are initialized inside the constructor. But here is java I see that I can initialize then while declaring, wh开发者_开发问答ich is different from C++.

So, I my question was which is the best/traditional practice to initialize the field members of any class. Is it...

  • at the time to declaring?

    class testClass { private int x = 100; }

  • using non-static scope?

    class testClass{ private int x; { x = 100; } }

  • or inside of a constructor?

    class testClass{ private int x; testClass(){x = 100;} }

( Because I of my background I am a little biased towards initializing field members inside of a constructor.)


I don't think there is a 'best practice' for initializing member variables. Obviously in Java you can initialize them in the declaration which is fine, or you can do it from the constructor. Unless you need to do something complicated (i.e. obtain a reference to a DataSource or something like that which might only be available with arguments passed in to the constructor).

In other words, there isn't a 'right way' of doing it, consistency is probably more important.

That said, bear in mind that Java will initialise uninitialised member variables for you if you don't do it. e.g. int variables will be set to 0, boolean variables will be set to false, any objects will be set to null, etc.


You should write the code which appears to be the simplest and clearest. I prefer declaring and initialising a simple value in one line and breaking up more complex lines.

You might find this notiation interesting.

private final List<String> words = Arrays.asList("one", "two", "three");

or using double brace notation.

private final Map<String, Integer> map = new LinkedHashMap<String, Integer>() {{
    put("one", 1);
    put("two", 2);
    put("three", 3);
}};


Though there is no 'best practice' there are some situations where certain methods work best.

For example, if you have a simple initialization value, then you can do it along with declaration.

If you have complex initialization logic (e.g array initialization), it can go inside the constructor.

Initializer blocks (non-static scope) are useful if you want to share common initialization code across constructors.

You can look at following link for more details http://download.oracle.com/javase/tutorial/java/javaOO/initial.html


Don't know if I get your question right but do you want to know how to initialize variables in a class?

    private String s;

public EditListener(String s){
    this.s = s;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜