developer
developer

Reputation: 9478

why public constructor should be provided in javabean class

I heared rules of JavaBean, in which first and main rule is , for every JavaBean class explicitly programmer should provide public default constructor . Please can anyone explain why do we need to provide default constructor for JavaBean

UPDATE :

Please explain clearly, why jvm will not provide default constructor for JavaBeans and how jvm reacts on providing default constructor

Upvotes: 5

Views: 11674

Answers (5)

diodfr
diodfr

Reputation: 99

This what wikipedaia says Java Bean Wikipedia article

The class must have a public default constructor (no-argument). This allows easy instantiation within editing and activation frameworks.

Actually it is esay to instanciate a class by introspection if it gets a default constructor

 getClass().getClassLoader().loadClass("mypackage.myclass").newInstance();

Upvotes: 0

McDowell
McDowell

Reputation: 108899

I suspect this is a misunderstanding of the difference between syntax and the generated class.

public class Alpha {
}

public class Beta {
  public Beta() {}
}

In Alpha the default constructor is implicit; in Beta it is explicit. Both have default public constructors as per the JavaBean spec.

public class Gamma {
  private final Type t;
  public Gamma(Type t) {
    this.t = t;
  }
}

On the other hand, Gamma does not meet the requirement as there is no public no-args constructor. There would be no way to instantiate this object without context about how to populate the constructor.

Upvotes: 0

Don Roby
Don Roby

Reputation: 41137

I heared rules of JavaBean, in which first and main rule is , for every JavaBean class explicitly programmer should provide public default constructor . Please can anyone explain why do we need to provide default constructor for JavaBean

JavaBean instances are created by reflective calls to the no-arg constructor. So there has to be such a constructor.

Please explain clearly, why jvm will not provide default constructor for JavaBeans and how jvm reacts on providing default constructor

The jvm will provide a default constructor for a JavaBean if you have explicitly provided no constructors. If you do provide a constructor, you must provide a no-arg constructor besides any that you define with parameters.

Upvotes: 17

reederz
reederz

Reputation: 971

We might add some other contructors to our bean which take parameters, and if we have not included Default constructor in our class, other constructor would shadow it, thus making it not a valid bean anymore.

Upvotes: 1

Johannes
Johannes

Reputation: 763

In my experience it is to prevent the situation where someone adds a constructor with parameters, and thus effectively removes the default constructor. By implementing the default constructor explicitly that is more unlikely to happen.

Upvotes: 0

Related Questions