Spook Spook - 11 months ago 112
Android Question

How to group common initializations in constructors?

I'm writing an Android application in Java. My class has two constructors - one is used when data is being passed directly and the second if class should deserialize the data from bundle. Everything looks more like the following:

public class MyClass {

private final ObservableInt myField;
private final int data;

public MyClass(int data) {

myField = new ObservableInt();
myField.addOnChangedListener(myListener);

this.data = data;
}

public MyClass(Bundle bundle) {

myField = new ObservableInt();
myField.addOnChangedListener(myListener);

this.data = bundle.getInt("SomeName");
}
}


Consider the above a simple example. I have a lot more final fields to fill and also a lot more
data
-type fields.

Now note, that this code is repeated in each constructor:

myField = new ObservableInt();
myField.addOnChangedListener(myListener);


I'd like to refactor it to single place to avoid DRY problems. I tried to create private constructor and call
this()
in each of the constructors above, but the compiler complains, that "data" field might not have been initialized and I don't want to pass it via parameter to that private constructor, because in my case there are a lot of
data
's to be filled.

Answer Source

You could try to use initializers like that:

public class MyClass {
    private final ObservableInt myField  = new ObservableInt();
    private final int data;
    {
       myField.addOnChangedListener(myListener);
    }

    public MyClass(int data) {
        this.data = data;
    }

    public MyClass(Bundle bundle) {
        this.data = bundle.getInt("SomeName");
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download