2

Possible Duplicate:
Should I initialize variable within constructor or outside constructor

I have here two examples on how to initialize a field (instance variable) in a class. My question is: what's the difference between them? Which one is the best and why?

EXAMPLE 1:

public class Example1 {
        private Object field;
        public Example1() {
            field = new Object();
        }
    }

EXAMPLE 2:

public class Example2 {
        private Object field = new Object();
        public Example2() {
        }
    }
Community
  • 1
  • 1
jcdmb
  • 3,016
  • 5
  • 38
  • 53

3 Answers3

4

Your first example is initializing the instance variables in the constructor.

The second example is initializing them when the class itself is instantiated, prior to the execution of code in your constructor, after the execution of any code in the superclass constructor. (If called.)

If you have instance variables that are always going to be initialized the same way regardless of which constructor is called, then you should use the second method. If the initialization of your instance variables depends on which constructor is called, then the first method is better. For example:

public class Dog {
    private int numLegs = 4;
    private String name = "Fred";

    public Dog() {
    } 

    public Dog(String name) {
        this.name = name;
    }
}

Note in the above example that you can actually use both - initialization in the constructor, and during the instantiation of your object.

Dog myDog = new Dog(); // This dog's name is Fred
Dog myDog = new Dog("Spot"); // This dog's name is Spot
Craig Otis
  • 31,257
  • 32
  • 136
  • 234
2

If you have multiple constructors, then you can try this rule:

If the member is initialized to the same value, initialize it inline. Otherwise, initialize it (assign it, really) in the constructor.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

In Example 1:

field is initialized to null, C'tor is called, field is assigned to a reference of Object. C'tor completes.

In Example 2:

field will be initialized to a reference of Object. C'tor is called, C'tor completes.

Acc. to me, Example 2 should be avoided untill unless it's a static reference.

Azodious
  • 13,752
  • 1
  • 36
  • 71
  • That's really missing the point that variables in Java are really references, so "initializing to null" isn't really that terrible. In your Ex 1, the second time it should be "`field` is assigned a reference to the object", and in Ex 2 it should be "`field` is initialized to a reference to the object"... – Kerrek SB Nov 26 '11 at 15:25