gihanmu
gihanmu

Reputation: 134

Why did it become a convention to create a non-arg constructor in a javabean?

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.

Upvotes: 1

Views: 678

Answers (5)

mrjoltcola
mrjoltcola

Reputation: 20842

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();

Upvotes: 0

Andrew Luo
Andrew Luo

Reputation: 927

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.

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200166

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.

Upvotes: 2

Erwin Smout
Erwin Smout

Reputation: 18408

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.

Upvotes: 2

chiastic-security
chiastic-security

Reputation: 20520

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.

Upvotes: 0

Related Questions