43

Possible Duplicate:
What's the point of beans?

What is a javabean? What is it used for? And what are some code examples? I heard it is used for something to do with getter and setter methods? I'm quite confused about what a java bean is and where you even access it. I googled it but couldn't find a definite answer.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Ryan Glenn
  • 1,325
  • 4
  • 17
  • 30
  • 9
    FWIW, this is the first Stack Overflow question to appear when I search for information about what a Java Bean is on Google. Very useful as a "signpost" question. – Knowledge Cube May 07 '17 at 02:19

4 Answers4

57

Java Bean is a normal Java class which has private properties with its public getter and setter method.

Java Beans are generally used as helper class.

Example -

public class User implements java.io.Serializable {

    private String name;
    private Integer age;

    public String getName(){
        return this.name;
    }

    public void setName(String name){
        this.name = name;
    }

    public Integer getAge(){
        return this.age;
    }

    public void setAge(Integer age){
        this.age = age;
    }
}

Implementing Serializable is not mandatory but is very useful if you'd like to persist or transfer Javabeans outside Java's memory, e.g. in harddisk or over network.

Places where JavaBeans are used?

Community
  • 1
  • 1
Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37
  • 3
    what about public default constructor ? – Ilya Buziuk Aug 12 '15 at 08:51
  • 1
    @IlyaBuziuk According to [this](http://stackoverflow.com/a/2291964/3775798), a public default constructor will be automatically provided by Java if one is not explicitly defined. I would take that to mean you should be safe omitting one for your bean definition. – Knowledge Cube May 07 '17 at 02:25
  • 9
    So if it's just a normal class, why even bother calling it a bean? I don't understand D: – SeriousLee Jul 04 '18 at 08:37
28

JavaBeans are reusable software components for Java. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a 0-argument constructor, and allows access to properties using getter and setter methods.

Advantages

  • A Bean obtains all of the benefits of Java's "write once, run anywhere" paradigm.
  • The properties, events, and methods of a Bean that are exposed to another application can be controlled.
  • Auxiliary software can be provided to help configure a Bean.
  • The configuration settings of a Bean can be saved in a persistent storage and can be restored at a later time.
  • A Bean may register to receive events from other objects and can generate events that are sent to it.

Disadvantages

  • A class with a nullary constructor is subject to being instantiated in an invalid state. If such a class is instantiated manually by a developer (rather than automatically by some kind of framework), the developer might not realize that he has instantiated the class in an invalid state. The compiler can’t detect such a problem, and even if it’s documented, there’s no guarantee that the developer will see the documentation.
  • Having to create a getter for every property and a setter for many, most, or all of them, creates an immense amount of boilerplate code.

Example :

package beans;

/**
 * Class <code>PersonBean</code>.
 */
public class PersonBean implements java.io.Serializable {

    private String name;

    private boolean deceased;
    static final long serialVersionUID = 1L;

    /** No-arg constructor (takes no arguments). */
    public PersonBean() {
    }

    /**
     * Property <code>name</code> (note capitalization) readable/writable.
     */
    public String getName() {
        return this.name;
    }

    /**
     * Setter for property <code>name</code>.
     * @param name
     */
    public void setName(final String name) {
        this.name = name;
    }

    /**
     * Getter for property "deceased"
     * Different syntax for a boolean field (is vs. get)
     */
    public boolean isDeceased() {
        return this.deceased;
    }

    /**
     * Setter for property <code>deceased</code>.
     * @param deceased
     */
    public void setDeceased(final boolean deceased) {
        this.deceased = deceased;
    }
}

refer http://en.wikipedia.org/wiki/JavaBeans

As per comment from @Andy I accept we should declare serialVersionUID. As per Java Docs

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members. Array classes cannot declare an explicit serialVersionUID, so they always have the default computed value, but the requirement for matching serialVersionUID values is waived for array classes.

if you don't explicitly specify serialVersionUID, a value is generated automatically - but that's brittle because it's compiler implementation dependent.

Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
  • This example looks incorrect - "The serializable class PersonBean does not declare a static final serialVersionUID field of type long" – Andy Mar 19 '20 at 13:13
  • @Andy if you don't explicitly specify serialVersionUID, a value is generated automatically - but that's brittle because it's compiler implementation dependent. That is why it is recommended to specify. I have edited my answer, Thanks to point it out. – Hemant Metalia Mar 20 '20 at 04:00
9

Well, the JavaBean API defines a number of conventions regarding to JavaBeans. According to Wikipedia:

The required conventions are as follows:

  • The class must have a public default constructor (no-argument). This allows easy instantiation within editing and activation frameworks.
  • The class properties must be accessible using get, set, is (used for boolean properties instead of get) and other methods (so-called accessor methods and mutator methods), following a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters must receive only one argument.
  • The class should be serializable. It allows applications and frameworks to reliably save, store, and restore the bean's state in a fashion independent of the VM and of the platform.

Quite often, these are the most common types of classes that can be found in an application, as they can be used to model the data that is used. An example of such a bean can be seen below:

public class Person implements Serializable
{
  private String name;
  private boolean alive;

  public Person()
  {
    // constructor logic...
  }

  public String getName()
  {
    return name;
  }

  public void setName(String name)
  {
    this.name = name;
  }

  public boolean isAlive()
  {
    return alive;
  }

  public void setAlive(boolean alive)
  {
    this.alive = alive;
  }
}

As you can see, properties are reflected in the getters and setters.

HTH

Crollster
  • 2,751
  • 2
  • 23
  • 34
3

If you are talking about java-beans and NOT EJB Beans, then here is the explanation...

1. A JavaBean has a constructor that takes no arguments.

2. A JavaBean has a set of properties.

3. A JavaBean has accessor (getXxx, or isXxx for Boolean properties) methods and mutator methods (setXxx) that allow access to its underlying properties.

The 3rd point states a java class with private instance variables and public getter, setter.

eg:

import java.util.Date;

public class User {
    private Date loginDate;
    private String name;
    private String password;

    public User() { }

    public Date getLoginDate() {
        return loginDate;
    }

    public String getName() {
        return name;
    }

    public String getPassword() {
        return password;
    }

    public void setLoginDate(Date loginDate) {
        this.loginDate = loginDate;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void delete() {
        // code to delete user from database
    }

    public void update() {
        // code to update user in database
    }

    public static User getUser(String name) {
        // code returning a new User object
        // populated from the database
    }
}
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75