JAVA BEANS
JavaBean
A JavaBean is a Java class that should follow the 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 JavaBean?
According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides easy maintenance.
Simple example of JavaBean 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 JavaBean class?
JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object. The feature can be of any Java data type, containing the classes that you define.
A JavaBean property may be read, write, read-only, or write-only. JavaBean features are accessed through two methods in the JavaBean's implementation class:
1. getPropertyName ()
For example, if the property name is firstName, the method name would be getFirstName() to read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be setFirstName() to write that property. This method is called the mutator.
Advantages of JavaBean
The following are the advantages of JavaBean:
- The JavaBean properties and methods can be exposed to another application.
- It provides an easiness to reuse the software components.
Disadvantages of JavaBean
The following are the disadvantages of JavaBean:
- JavaBeans are mutable. So, it can't take advantages of immutable objects.
- Creating the setter and getter method for each property separately may lead to the boilerplate code.

Comments
Post a Comment