A Java Bean is a java class that should follow following conventions:

  • It should have a no-arg constructor.
  • It should be Serializable.
  • It should provide methods to set and get the values of the properties, known as getter and setter methods.

Why use Java Bean?

According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object, so we can access this object from multiple places. Moreover, it provides the easy maintenance.

Simple example of java bean class

//Employee.java  
  
package mypack;  
public class Employee implements java.io.Serializable{  
private int id;  
private String name;  
  
public Employee(){}  
  
public void setId(int id){this.id=id;}  
  
public int getId(){return id;}  
  
public void setName(String name){this.name=name;}  
  
public String getName(){return name;}  
  
}

How to access the java bean class?

To access the java bean class, we should use getter and setter methods.
package mypack;  
public class Test{  
public static void main(String args[]){  
  
Employee e=new Employee();//object is created  
  
e.setName("Arjun");//setting value to the object  
  
System.out.println(e.getName());  
  
}}