Java - when to initialize objects [duplicate]
Possible Duplicate:
Which one is the better way of code writing?
Hi everyone,
I would like to know if there is any difference between two initialization methods below. If so, which method is considered as a best practice? Thanks in advance.
Class Foo {
List myList = new ArrayList();
}
Class Foo {
List myList;
public Foo() { 开发者_开发问答
myList = new ArrayList();
}
}
if you know what you are going to initialize a class member to, it is better to do it as the first example. In that case, you are creating a new ArrayList. You should also make it private final
unless you intend to change it through class methods.
I only initialize things in the constructor if the constructor takes arguments that are applied to members - otherwise I do it outside of it.
I think it's a matter of style... I prefer the former when possible, but the latter when necessary.
Personally I prefer the second (creating new objects in constructor). But there's no difference between them.
The only difference maybe if you have two objects created by both methods, object which is created by first method is created first and object which is created in constructor would be created after it.
精彩评论