What Is a Java Bean?

Java bean is a reusable class which follows certain standards in terms of syntax. Mainly bean classes are used to encapsulate many data or objects inside one object. So that that single object can be sent/stored. A JavaBean is a Java Object which is serializable(So that we can send it over network or store it in a File), has a pubilc 0-argument constructor(Default Constructor), private variables and public getter and setter methods.

Advantages:

  • Write Once, Use it multiple times
  • Send multiple objects within 1 object
  • Java Bean provides Data sharing architecture so that a bean can be used to receive events from other objects.
  • Many frameworks understands Bean standards and take Bean class as input

JavaBean conventions:

  • public default constructor
  • Variables with access protection e.g private, protected, public, default
  • Public setter and getter for each variable to assign/access the values
  • Must implement serializable interface so that object can be sent/stored

Example:

import java.io.Serializable;

public class Employee implements Serializable 
{
    private int id;
    private String name;
    private long contact;
    
    public Employee()
    {
        id = 0;
        name = "";
        contact=0;        
    }

    public long getContact() {
        return contact;
    }

    public void setContact(long contact) {
        this.contact = contact;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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