Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization in definition vs. initialization in constructor [duplicate]

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

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

and using a constructor to initialize it?

class Example {
    public Sample sample_attribute;

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

I could not think of any practical difference, is there one? Otherwise, are there cases in which one method is better than the other, even if they have the same result?

like image 467
scristalli Avatar asked Apr 25 '26 07:04

scristalli


1 Answers

The initialization order is matter here.

  1. Set fields to default initial values (0, false, null)
  2. Call the constructor for the object (but don't execute the body of the constructor yet)
  3. Invoke the constructor of the superclass
  4. Initialize fields using initializers and initialization blocks
  5. Execute the body of the constructor

So, first case will be initialize the variable sample_attribute in 4th step, second will initialize the variable sample_attribute in 5th step. It's all depends on your requirement.

If you want to access any of the variables from Constructor, you need to use 1st case.

like image 64
Abimaran Kugathasan Avatar answered Apr 27 '26 19:04

Abimaran Kugathasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!