Good style to call extended constructor from non-parameterized constructor?

I just discussed with some colleagues about Java constructors, design patterns, and a good way to initialize objects with a non-parameterized constructor, if I usually wait for some parameters.

One of the older ones came up with his own way of implementation, 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, what is a good style and what exactly is its behavior?

From what I understand it should be:

  • he first creates an Object, and then calls a parameterized constructor to create a new object of this type with these parameters and sets his own link to the new one. Thus, the GC must then delete the first one created.
+4
source share
2 answers
 So the GC has then to delete the first created one. 

No. Only 1 instance is ever created when creating a chain of constructors.

To answer your question, yes, this is a good style, assuming you need both foo() and foo(int, int, int)

+6
source

This is called the telescopic constructor template . In Efficient Java, Joshua provides alternatives with suggestions for use when.

+6
source

Source: https://habr.com/ru/post/1387004/


All Articles