Why do we need a default no argument constructor in many Java related APIs? Like as a general rule all java bean classes or entity classes (JPA etc) or JAX-WS implementation classes require a explicit no argument constructor.
If by default Java provides a no argument constructor then why most of these standards require a explicit constructor?
Java only provides a default no-argument constructor if no other constructors are defined. Thus, if you have other constructors you must explicitly define a no-arg constructor yourself.
These frameworks use the reflection API and look at method names to determine how to set properties. The arguments of a constructor can only be found by type, not by name, so there is no way for the framework to reliably match properties to constructor args. Therefore, they require a no-arg constructor to create the object, then can use the setter methods to initialise the data.
Some frameworks may support #ConstructorProperties as an alternative.
I believe frameworks that require public nullary constructors do so because they use reflection to instantiate types, e.g. through Class.newInstance().
As to why the default constructor may not work for this case, here's the relevant JLS section:
JLS 8.8.9 Default Constructor
If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:
if the class is declared public, then the default constructor is implicitly given the access modifier public;
if the class is declared protected, then the default constructor is implicitly given the access modifier protected;
if the class is declared private, then the default constructor is implicitly given the access modifier private;
otherwise, the default constructor has the default access implied by no access modifier.
So in a public class, the default constructor would have the right visibility, but otherwise an explicitly public one must be provided.
A constructor is needed to initialise any non-default values and can contain side effects which are needed.
If you have a programing style which encourages a minimal constructor for data transfer objects this would seem unneccasary, but the libraries have chosen not to assume any programming style for the constructors.
You can write a library which doesn't assume a default constructor, but you have to make assumptions about what the constructor would do and wouldn't do. i.e. I have written such libraries but was able to also mandate what a constructor was allowed to do so that not calling it directly was safe.
Java only supplies a no-arg constructor if no other constructor is applied. In a number of Java APIs (e.g. JPA, Serialisation and many others that build objects from an external representation) an instance of the object is required before the data values of the object can be set, as the definition of how the values are applied are defined through instance members of the object (e.g. readExternal(ObjectInput)). If a class only has a constructor that takes some arguments then it may not be possible for the library to construct an instance unless a separate no-arg constructor is defined.
It is worth noting that this is a design choice by the implementer of the particular library, it is possible to build an API/Framework that can externalise and recreate objects that don't have a no-arg constructor (defining a separate factory class is one approach). The pattern of requiring a no-arg constructor turned up first in Java Serialisation (I think) and has been adopted as the de-facto standard approach on other libraries (e.g. JPA). The weakness of this approach is that it prevents the use of immutable objects.
Two reasons:
1) to avoid NullPointerException if an instance data field of a reference data type is uninitialized. Providing an explicit constructor would give you the chance to initialize such data fields, if they have not been initialized when declared
2) for users who would like to use no-arg constructors; these are not automatically provided if other constructors exist
Many of these frameworks derive from the earlier ideas of "POJO" and especially JavaBeans. The smallest useful Java Object would, by convention, have a no-arg constructor and every member accessible through methods like get/setProperty1 and is/setProperty1 for booleans. If Classes follow that convention of the interface, tools and frameworks using reflection can work 'out of the box'.
Default No-Argument constructor provides default values to the object like 0 or null, hence it is mandatory in java coding.
Related
I know if I do not implement the default constructor in a spring data an exception will be thrown,actually I faced the same exception when I have to work databases. I never understand the reason. Please advise
First, for clarity, it's not the default constructor (you never explicitly implement the default constructor, that's why it's called a default), it's the zero-parameters constructor. (E.g., the one that Class#newInstance would call.)
You need to implement it in most object/relational mappers because they first create the object (with the zero-parameters constructor) and then assign its individual field values to it.
Having said that, if you don't implement any constructors, then the default constructor the compiler will provide should be sufficient for most OR mappers (I haven't used spring-data). By default, it's a zero-parameters constructor with the same accessibility as the class. But if you implement any constructors, the compiler won't create the default for you, and you'd have to supply the zero-parameters constructor yourself.
In Java, when a constructor is overloaded, the Default Constructor is not automatically included. While for compilation a Default Constructor is not required, I have read that it is good practice to include a Default Constructor along with the overloaded constructors.
Is this common professional practice or a few programmers option?
A default (no-argument) constructor is automatically created only when you do not define any constructor yourself.
If you need two constructors, one with arguments and one without, you need to manually define both.
It really depends; while it is common for DTOs to always have a default constructor (so that they adhere to Javabeans convention), if the constructor argument is a mandatory dependency (think a data access component in a service bean) it should be in every constructor, thus making the default constructor a bad choice.
As we can read here Hibenate requires no-arg constructor for all the #Entity classes. But isn't it true that java class has always implicit default constuctor, even if we don't declare one explicitly?
In my project I don't declare a no-arg constructor in my #Entity classes and eveything works fine. But on the other hand, I guess that Hibernate specification has been written carefully so maybe actually declaring explicitely default constructor may have some benefits?
If you create other constructor, java will not create implicit constructor.
There are no special benefits of defining the no-arg constructor explicitly for the Entity Classes (But remember that, Hibernate framework internally uses the no-arg constructor to populate entities through Java reflection API).
It is mandatory that the Hibernate Entity Bean Classes require no-arg constructors, which can be defined explicitly by the programmer (or auto. generated by Java).
One important point is that when you are defining your own constructor(s) for the class, you need to provide the no-arg constructor by yourself (because the compiler does not provide in this case).
In Hibernate, no-arg constructor is used to loading database entities via Reflection(that is used to examine or modify application behaviour at runtime).
The implementation of the default no arg constructor, is not mandatory even for Hibernate, because java automatically and implicitely manage it.
And the only case where you need to specify it is when you declare another parametrized constructor.
If you take a look at The No-Arg Constructor, you will see that:
Every class has at least one constructor. There are two cases:
If you do not write a constructor for a class, Java generates one
for
you. This generated constructor is called a default constructor. It's
not visible in your code, but it's there just the same. If you could
see it, it would look like this (for the class Dog):
public Dog() { } Notice that this default constructor takes no arguments and has a body that does nothing.
If you do write a constructor for your class, Java does not generate
a
default constructor. This could be a problem if you have pre-existing
code that uses the default constructor.
If you don't define any constructors, the compiler will generate the default one, as described in the JLS:
If a class contains no constructor declarations, then a default
constructor with no formal parameters and no throws clause is
implicitly declared.
If the class being declared is the primordial class Object, then the
default constructor has an empty body. Otherwise, the default
constructor simply invokes the superclass constructor with no
arguments.
This means that you don't have to explicitly implement the no-arg constructor for a Hibernate entity as long as:
You don't have any other constructors in the entity class;
The extended superclass has a no-arg constructor without a throws clause for any checked exceptions.
Java class might have no implicit default constructor.
Suppose, you have such a class:
public class A {
public A(String st) {}
}
Eventually the only constructor would be A(String st), not A(String st) and A().
I know
A JavaBean is just a standard
All properties private (use getters/setters)
A public no-argument constructor
Implements Serializable.
Source
We all know it is not required to provide a non argument constructor in a class, because if we have not specified any constructor in our class java compiler will create a non argument constructor. If so why programmers wanted to create a non argument constructor in a javabean as a convention.
You are confusing requirements on the JavaBean class with the requirements on its source code. No part of the JavaBeans specification deals with how your source code must look like, it is strictly about the resulting class.
So yes, each JavaBeans class must provide a nullary constructor, and how you achieve that with source code (or even with a bytecode generator) is completely up to you.
It is considered good practice by some to always include the non-arg constructor in your code, because that prevents the scenario where a later maintenance introduces another constructor, thereby discarding the implicit non-arg one, thereby breaking any external code that relies on it.
You don't have to create it explicitly. There's no rule saying you have to do that. Even for a JavaBean, it's fine to leave the compiler to create one for you (as long as you're not providing another one, in which case you'd need an explicit no-arg constructor too).
But there does need to be one, explicit or implicit, because the ORM needs to be able to create instances.
You'd want to create a no argument in these cases:
1) You want to do some logic in the no argument constructor, so can't use the default.
2) You have other constructors that take arguments, in that case no default no-arg constructor will be provided for you.
point 2 implies that having an explicit no arg constructor to start with allows you to add future constructors with arguments without worrying about losing the implicit no-arg constructor.
Without one many API internals like ORMs or IOC containers can't instantiate the object in order to proceed with setting the bean properties from the data source or other bean dependencies.
Many do approximately this:
Class<?> clazz = Class.forName("com.foo.BeanClass");
Constructor<?> constructor = clazz.getConstructor();
Object bean = constructor.newInstance();
The GWT tutorial says
As of GWT 1.5, it must have a default (zero argument) constructor (with any access modifier) or no constructor at all.
So, when the default constructor is only used by the Serialization mechanism, wouldn't it be useful to make it private? This way, clients of the class don't accidentally call the default constructor, and the visible interface becomes smaller.
Or does it somehow affects the Serialization mechanism in any other way?
The GWT tutorial statement appears to apply to a specific requirement of GWT itself, or else it reiterates a common misunderstanding. The Java requirement is that the nearest non-serializable base class has an accessible default constructor. Not the serializable class itself.
the complete process of serialization involves also deserialization, in which the java object will be reconstructed.
Therefore adding a private constructor to a serializable class will not work on the way back (deserialization) and since you can't have both private and public constructors with the same arguments (in GWT case the default - no args - one) stick with the public modifier.
cheers!
**WARNING THIS ANSWER IS NOT ABOUT HOW THE GWT COMPILER HANDLES ITS REQUIRED DEFAULT NO-ARG CONSTRUCTOR**
If you put it private, Serialization won't work.
From Javadoc :
"The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime."
So yes, it will affect the Serialization process.
You could deprecate or comment this constructor indicating it is only used for Serialization purpose.
See here for details about serialization.