Java Bean


A JavaBean is a Java class that has to comply with the subsequent conventions:

  • It needs to have a no-arg constructor.
  • It needs to be Serializable.
  • It needs to offer strategies to set and get the values of the properties, called getter and setter strategies.

Why use JavaBean?

According to the Java white paper, it's miles a reusable software program component. A bean encapsulates many gadgets into one object in order that we are able to get entry to this object from more than one place. Moreover, it gives smooth maintenance.

Easy Example of Java Bean Class


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?

We have to make use of getter and setter methods, to access the java bean class:

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  

Note: Two ways are there to give values to the object. The first way is by making use of the constructor and the second way is by making use of the setter method.

Properties of JavaBean

A JavaBean property is an identified attribute that will be retrieved by the user of the Component. The attribute might be of any Java data type, having the classes that you explain.

A JavaBean property can be examined, write, examine-only, or write-only. JavaBean functions are accessed through techniques withinside the JavaBean's implementation class:

  1. getPropertyName ()

For example, if the property call is firstName, the technique call could be getFirstName() to examine that belonging. This technique is referred to as the accessor.

  1. setPropertyName ()

For example, if the property call is firstName, the technique call could be setFirstName() to jot down those belongings. This approach is known as the mutator.

Advantages of JavaBean

Benefits of JavaBean:/p> are given below:

  • The JavaBean properties and strategies may be exposed to any other application.
  • It offers an easy to reuse the software program components.

Disadvantages of JavaBean

Negative aspects of JavaBean are given below:

  • JavaBeans are mutable. So, it cannot take advantage of immutable objects.
  • Creating the setter and getter technique for every asset one at a time may also cause the boilerplate code.