In this shot, we will learn about JavaBean and why we use them when building Java applications.
To understand why we use JavaBean, we first need to know what a JavaBean is.
A JavaBean is a Java class that follows a certain standard:
JavaBean class properties should be set to private
– accessing /mutating these properties is done using getters/setters methods.
A JavaBean class should have a public no-argument constructor.
A JavaBean class should implement the java.io.Serializable interface. The Serializable
interface allows the saving, storing, and restoring of a JavaBean’s state while in use.
There is no syntactic difference between a regular Java class. The standard stated above is what differentiates an ordinary Java class from a JavaBean class.
Let’s see an example of a simple JavaBean class.
package demo;public class User implements java.io.Serializable{ // implementing the Serializable interfaceprivate int id; // private propertyprivate String name; // private propertypublic User(){// no-argument constructor}public void setId(int id){ // mutator methodthis.id=id;}public int getId(){ // accessor methodreturn id;}public void setName(String name){ // mutator methodthis.name=name;}public String getName(){ // accessor methodreturn name;}}
In the above code, we can see that:
The User
class implements the java.io.Serializable
interface.
All properties of the class are set to private
.
Each property has a getter and setter method.
And the constructor has no argument at all.
A fundamental principle of software development is “Don’t Repeat Yourself” (DRY); a JavaBean is a reusable software component that can be used all around a Java application, adhering to the DRY principle.
Java is an Object-Oriented Programming (OOP) Language. A core concept of OOP is encapsulation. A JavaBean encapsulates many objects into a single object (the bean).
We can expose JavaBean events, properties, and methods to another application.
Even though JavaBeans are designed to run on the client-side, one can develop server-side beans.