Is there any advantage for either approach?
Example 1:
class A {
B b = new B();
}
Example 2:
class A {
B b;
A() {
b = new B();
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There is additionally the initialization block, which is as well put in the constructor(s) by the compiler:
Check Sun’s explanation and advice
From this tutorial:
Additionally, you might want to lazily initialize your field. In cases when initializing a field is an expensive operation, you may initialize it as soon as it is needed:
And ultimately (as pointed out by Bill), for the sake of dependency management, it is better to avoid using the
newoperator anywhere within your class. Instead, using Dependency Injection is preferable – i.e. letting someone else (another class/framework) instantiate and inject the dependencies in your class.