Initialization in the definition versus initialization in the constructor

In Java, but also in other OO languages, is there a difference between initializing an attribute in its definition, as in

class Example {
    public Sample sample_attribute = new Sample();
}

and using the constructor to initialize it?

class Example {
    public Sample sample_attribute;

    public Example() {
        sample_attribute = new Sample();
    }
}

I could not come up with any practical difference, is there any? Otherwise, there are cases when one method is better than another, even if they have the same result?

+3
source share
3 answers

The initialization order matters here.

  • Set fields for initial default values ​​(0, false, null)
  • A constructor call for an object (but do not execute the body constructor yet)
  • Superclass Constructor Call
  • Field initialization using initializers and initialization blocks
  • Run constructor body

, sample_attribute 4- , sample_attribute 5- . .

, 1- .

+3

, , , . , , , .

0

. new Sample() ,

0

All Articles