Why use an empty constructor?

I recently read some Java and came across something (an idiom?), New to me: in a program, classes with multiple constructors would always include an empty constructor. For example:

public class Genotype { private boolean bits[]; private int rating; private int length; private Random random; public Genotype() { // <= THIS is the bandit, this one right here random = new Random(); } /* creates a Random genetoype */ public Genotype(int length, Random r) { random = r; this.length = length; bits = new boolean[length]; for(int i=0;i<length;i++) { bits[i] =random.nextBoolean(); } } /* copy constructor */ public Genotype(Genotype g,Random r) { random = r; bits = new boolean[g.length]; rating = g.rating; length = g.length; for(int i=0;i<length;i++) { bits[i] = g.bits[i]; } } } 

The first constructor does not seem to be a “real” constructor; it seems that in each case one of the other constructors will be used. So why is this constructor defined at all?

+6
java constructor coding-style
source share
10 answers

I'm not sure that the code you read was of high quality (in the past I looked at some bioinformatics code and, unfortunately, was often not written by professional developers). For example, this third constructor is not a copy constructor and, as a rule, there are problems in this code, so I won’t “read too much”.

The first constructor is the default constructor. It only initializes the minimum minimum and allows users to set the rest using getters and setters. Other constructors are often “convenience constructors” that help create objects with fewer calls. However, this often leads to inconsistency between the designers. In fact, there are recent studies that show that a default constructor followed by setter calls is preferred.

There are also certain cases where the default constructor is critical. For example, certain structures, such as digester (used to create objects directly from XML), use default constructors. JavaBeans usually use default constructors, etc.

In addition, some classes inherit from other classes. you can see the default constructor when the initialization of the parent object is "good enough".

In this particular case, if this constructor was not defined, it would be necessary to know all the details in advance. This is not always preferable.

And finally, some IDEs automatically generate a default constructor, it is possible that the person who wrote the class was afraid to eliminate it.

+9
source share

Is the object Serializable ?

In order to allow serialization of subtypes of non-serializable classes, the subtype can take responsibility for maintaining and restoring the state of public, protected and (if available) supertype packages. A subtype can take this responsibility only if the class that it extends has an available no-arg constructor to initialize the state of the class. Error declaring a Serializable class if it is not. An error will be detected at runtime.

During deserialization, fields of non-serialization classes will be initialized using the public or protected constructor of the no-arg class. The no-arg constructor must be available for a subclass that is serializable. Fields of serializable subclasses will be restored from the stream

+5
source share

Yes, I agree that an “empty” constructor does not always exist (in my experience, newcomers often make this mistake), although there are times when an empty constructor is enough. However, if an empty constructor violates the invariant that all members are created properly after construction , an empty constructor should not be used. If the constructor is complex, it is better to split the construct into several protected / private methods. Then use the static method or another Factory class to call secure build methods, if necessary.

What I wrote above is an ideal scenario. However, frameworks such as spring extract designer logic from code and into some xml configuration files. You may have getter and setter functions, but you can probably escape from the interface as described here .

+3
source share

The default constructor is NOT required.

If constructors are not defined in the class, then the default constructor (empty) will be created automatically. If you have provided any parameterized constructors, then the default constructor will not be created automatically, and it is better to create it yourself. Frames that use dependency injection and dynamic proxy creation at runtime usually require a default constructor. So it depends on the use cases of the class you are writing.

+1
source share

The default constructor is'nt is a good estimate for functional presentation. The default constructor is used if the object has global visibility in the method: for example, you want to write the actual state of the object in try / catch you can encode

 MyObejct myObject=null try{... }catch(Exception e){ log.error(myObject);//maybe print null. information? } 

or prefer

 MyObejct myObject=new Object(); try{... }catch(Exception e){ log.error(myObject);//sure print myobject.toString, never null. More information } 

?

Otherwise, creating an EMPTY object does not have much logic, but in my opinion, a NULL object is intrusive. You can read this post.

0
source share

This is NOT a copy constructor. Basically you want to create empty constructors when working with some frameworks. Should there be an empty constructor, of course, open or closed, but at least it allows you to control how the class is instantiated (or not).

0
source share

I usually write one constructor that completely initializes the object; if there are others, they all call this (...) the appropriate default settings.

The object must be 100% initialized and ready for use when it is created.

Some frameworks, such as Hibernate, require a no-arg constructor. The way they come up against best practices sometimes causes me concern.

0
source share

The presence of a default constructor and empty (empty) prevents the appearance of any trailing fields. This leads to a lot of variability when there is often not required.

The builder pattern allows you to mix these two styles and allow for more flexible initialization while maintaining immutability, hiding the constructor with a few arguments behind the factory.

0
source share

For some POJO classes or a simple class, the default constructor is useful when you sometimes want to do unit testing on a class using them. You do not need to mock them, you can create a new object with a default constructor and check the value set and get from them, or pass them as an argument.

0
source share

You want to create an empty constructor for the classes that extended this class, and since it was extended by the class ... the child now has a super that references the class above which it is the parent. In case the child did not specify super (material) ... the contents inside the link to other constructors, in order to use it, will now try to refer to the empty constructor.

I am not sure what the error will be. I am now coding my relationship with the parent and looking at things here.

I think I should add a moment when you create a constructor that is not empty, you lose the default by default, so now super (), which by default in the extended class, will not have a hint for anything. Of course, if you created extended classes to take care of super, indicating that it gets rid of super () by default, you will get around this, but that if someone wants to use your class and extends from it and doesn't understand, t is empty set when you could just created one.

This is my first post, but I wanted to understand how I understand it.

0
source share

All Articles