Initialization block vs constructor and initialization of variables

I am trying to clear the code of a class using initialization blocks in a way that I would never have done, and I'm just wondering if I am missing some information. The code is as follows:

@Entity
class MyClass extends BaseClass {

    @ManyToMany(fetch=FetchType.EAGER)
    private Set<OherClass> others;

    {
        if (others == null)
            others = new HashSet<OtherClass>();
    }

    public MyClass(){
        super();
    }

    //getters, setters and other stuff follows
}

I think there is no reason to prefer the code above:

@Entity
class MyClass extends BaseClass {

    @ManyToMany(fetch=FetchType.EAGER)
    private Set<OherClass> others = new HashSet<OtherClass>();
}

Or that:

@Entity
class MyClass extends BaseClass {

    @ManyToMany(fetch=FetchType.EAGER)
    private Set<OherClass> others;

    public MyClass(){
        this.others = new HashSet<OtherClass>();
    }
}

I asked my college, but the only thing he could answer was how the initialization block works, and other things that I already know. I wonder if there is some kind of subtle incorrect java behavior (even the old one has already been fixed) or frameworks (hibernate, spring) in case of serialization, reflection, saving the database, injection or any unusual situation that could make this code necessary.

+3
source
2
private Set<OherClass> others;
{
    if (others == null)
        others = new HashSet<OtherClass>();
}

Java. others == null true. ,

private Set<OherClass> others = new HashSet<OtherClass>();

Hibernate "" , . .

, , , , final. .

, , .

+5

, , , others , BaseClass , , MyClass, , others , . . , Java :

public class BaseClass {

    public BaseClass() {
        init();
    }

    public void init() {
        // do something...
    }

}

public class MyClass extends BaseClass {

    private Set<OtherClass> others;
    {
        others = new HashSet<OtherClass>();
        others.add(new OtherClass("hallo"));
        // or do more complicated stuff here
    }

    public MyClass() {
        super();  // explicit or may also be implicit
    }

    @Override
    public void init() {
        // use initialized others!!
        doSomething(this.others);
    }

    ....
}

, , .

, others , , .

+1

All Articles