MBZ
MBZ

Reputation: 27632

how to initialize a class field?

I have seen developers initialize their class fields in different ways. Three of them are very popular! What's the difference and is any of them more proper?

class Test {
    ArrayList<String> myArr = new ArrayList<String>(); // First Method 
}


class Test {
    ArrayList<String> myArr;
    public Test() {
        myArr = new ArrayList<String>(); // Second Method
    }
}


class Test {
    ArrayList<String> myArr;
    public Test() {
    }
    public void Init() {
        myArr = new ArrayList<String>(); // Third Method
    }
}

Upvotes: 0

Views: 398

Answers (4)

amicngh
amicngh

Reputation: 7899

1 and 2 are equivalent but if variable is static then behavior differs like below code

public class Test {
static String s="2"; // 1

Test()
{
    System.out.println(s);
    s="3"; //2
}

public static void main(String[] args) throws IOException {

    System.out.println("1="+s);
    new Test();
    System.out.println("1="+s); 
 }

In 1 initialization happens when class loads but if you initialize static variable in constructor (2) then value will be assigned when object is constructed.

3) On demand you are initializing variable.

class Test {
ArrayList<String> myArr;
public Test() {
}
public void Init() {
    myArr = new ArrayList<String>(); // Third Method
}
}

Upvotes: 1

ewan.chalmers
ewan.chalmers

Reputation: 16255

1 and 2 are more-or-less equivalent and also allow you to use the final modifier on the field.

(The difference is that in case 1, the field is initialized before constructor invocation, whereas in case 2, the field is initialized when the constructor is invoked.)

3 is a lazy initialization pattern.

Upvotes: 4

Maxime ARNSTAMM
Maxime ARNSTAMM

Reputation: 5314

It's about control and readability :

the first and the second are equivalent.

the second help you control the order of the initializations.

the third can offer delay (lazy init) like if you test your class and don't want to create everything.

Upvotes: 0

Attila
Attila

Reputation: 28802

There are not much differences between the first and the second: the difference is more syntactic.

In the first approach you place the declaration and the defintion together, so you won't forget to initialze the variable.

The second and thrid approaches allow more flexibility if you want to initialize differently based on some conditions.

The third is more for frameworks where you have to have a parameterless constructor and will call the "real" initializer method (With all the necessary parameters) separately. The third approach also allows easier "reset" of the object to its initial state.

Note: if you have a final field, you can only use the first or second approach, as it cannot be re-assigned once the intial assignment takes place and that assignment has to happen by the end of the constructor

Upvotes: 1

Related Questions