1

Is there any difference between these two ways of initialising class members?

In the class body:

public class A { private mB = new B(); public A() { } } 

Or in the constructor:

public class A { private mB = null; public A() { mB = new B(); } } 
1
  • i think both are same Commented Sep 3, 2013 at 11:11

5 Answers 5

4

In theory, there is a difference in the sequence of initialization. This is the sequence used by the JVM:

  1. Static statements/static blocks are executed.
  2. Instance variables are assigned default values
  3. Instance variables are initialized if the instance variable is assigned a compile time constant. Otherwise, it will be done with Item 5 (instance variables and instance initializers will be done together from the top to the bottom, in the order they are defined).
  4. constructor runs
  5. Instance initialization block(s) run after all the call(s) to super has(have) been completed but before the rest of the constructor is executed.
  6. Rest of the constructor is executed.

Also, if you initialize the fields in the constructor, it can mean that you might get some duplication. Personally, I think it doesn't matter much where you instantiate them, either in the constructor or in the fields, but the main point is that you are consistent about it. For me it helps having them instantiated in the field declaration so I know which fields are always there, and which fields are optional. Hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

3

The instance initializer run first and then values in constructor are initialized. You can study order of execution of initialization blocks and constructors

Comments

2

If B() constructor threw a checked exception then this

private mB = new B(); 

would be a compile time error, while in constructor you could catch it or declare in throws clause

Comments

1

I would do the one you believe is simpler.

The main difference is that if you add another constructor to the first, you don't have to repeat the initialisation.

Comments

1

Your first example initializes the variable once: your second example, twice. First is to be preferred, especially if there are multiple constructors, unless there is an exception involved of course.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.