Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good style to call advanced constructor from unparametrized constructor?

I was just discussing with some colleagues about Java constructors, design-patterns and good way to initialize objects with a unparametrized constructor if I normally await some parameters.

One of the older ones came up with his way of implementing always something like:

public class Foo {

public Foo() {
this(0,0,0);
}

public Foo(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
..
}

My question is, is that good style and what is its behaviour exactly?

From what I understand should be:

  • it instantiates first an Object and then calling the parametrized constructor to construct a new object of that type with that parameter settings and set its own reference to the new one. So the GC has then to delete the first created one.
like image 331
Stefan Avatar asked Dec 17 '22 06:12

Stefan


1 Answers

So the GC has then to delete the first created one.

No. Only 1 instance is ever created when chaining constructors.

To answer your question, yes, it's good style, assuming you need both foo() and foo(int, int, int)

like image 96
cherouvim Avatar answered Jan 11 '23 23:01

cherouvim