1

Possible Duplicate:
Instance variable initialization in java

Hello, can someone tell me what the difference / pros or cons of creating an object with the declaration of the class instance vars ie..

public class ClassName{
    Object o = new Object();
}

to in the contructor

public class ClassName{ 
    Object o;
    public ClassName(){
        o = new Object();
    }
}

thank you!

Community
  • 1
  • 1
Dori
  • 18,283
  • 17
  • 74
  • 116
  • possible duplicate:http://stackoverflow.com/questions/3918578/should-i-initialize-variable-within-constructor-or-outside-constructor – Emil Oct 25 '10 at 11:37

3 Answers3

1

Well in the upper case there's always an object made if the class is loaded, inthe lower case you're only create the object if the class is instantiated.

I guess the second way is always the way to go if you don't make the field o static.

Akku
  • 4,373
  • 4
  • 48
  • 67
0

In your case it is effectively the same.

The difference would be if

  1. there were other fields that depend on field "o" or
  2. there were other Constructors
Peter Knego
  • 79,991
  • 11
  • 123
  • 154
0

I usually construct it at the declaration if it's a "trivial" default-constructor thing. I put it in the constructor if

  • I need different initializations for different constructors (obviously)
  • The initialization depends on some argument of the constructor (obviously)
  • The initialization of the field requires any work, such as getting the value from some where else.

As always when there is no semantical difference, rule of thumb is: Go for the alternative that you find most readable.

aioobe
  • 413,195
  • 112
  • 811
  • 826