1

What's the difference between using the keyword new in a constructor and in the data portion of a class?

It's easier with an example:

Approach1:

public class Foo{
    RandomClass bar = new RandomClass();
    Foo(){}
}

Approach2:

public class Foo{
    RandomClass bar;

    Foo(){
        bar = new RandomClass();
    }
}

Can someone please explain the difference between those?

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
Arch1tect
  • 4,128
  • 10
  • 48
  • 69

2 Answers2

2

There is actually no difference. The Java compiler will actually generate the exact same code for both. They are completely equivalent. But as for style, the first one is generally preferred.

tbodt
  • 16,609
  • 6
  • 58
  • 83
0

These two kinds of initialization seems almost have no difference, after test it myself, what I found about that is only execution sequence distinction.
while new a instance in main method, it will first enter the constructor to create a instance as your order.
At this time, your program will execute the field default value position, which is what you put at RandomClass bar = new RandomClass();
your member field will be filled by the value of default value you have put there.
and this is what we called default value for member field.
after that sentence, main thread will jump back to the constructor, and execute
bar = new RandomClass();
which means your default setting for a member field will be override by constructor program.

In a conclusion there seems have no too many difference between these two initialization method. and personally speaking, I would like to have a default value for each member field that should have one, or I will have a init() method in every constructor to unify initialization style .

Rugal
  • 2,612
  • 1
  • 15
  • 16