Sunday, March 5, 2017

What is Java Bean with examples

In this post we will learn What is Java Bean and what are the advantages of Beans and why we use Beans in java. We will learn all these questions along with examples. A Java Bean is a java class that has been designed to be reusable in a variety of different environments.
The following are the charcaterstics that distinguish a Java Bean from other Java classes:

1) The Java Bean class must implement either Serializable or Externalizable
2) The Java Bean class must have no-arg contrustor
3)All Java Bean instance variables should be private
4)All Java Bean properties must have public setter and getter methods.


Why use Java Bean:

The Software industry has also been seeking the benefits of reusability and interoperability of a component based approach. That means Java Bean is reusable software component. For example, a Hardware Designers have a wide variety of components that can be integrated together to construct a System. Such as Resistors,capacitors and Integrated Circuits are more advanced functionality. All of these different parts can be reused. It is not necessary to build these capabilities each time a new system is needed. When a new version of a component becomes available,it should be easy to incorporate this functionality into existing code. So Java Bean provides just such an Architecture. That means Java Beans provides that an easy maintenance. 



Example:

class Employee implements Serializable{
private int Id;
private String name;
private int salary;
public Employee()
{
}
public Employee(String name,int salary)
{
this.name=name;
this.salary=salary;
}
public int getId()
{
return Id;
}
public void setId(int Id)
{
this.id=id;
}
public String getName()
{
return name;
}
public void setName()
{
this.name=name;
}
public int getSalary()
{
return salary;
}
public void setSalary()

{
this.salary=salary;
}
}

Note: In the above example you will find Employee class implements Serialization,since when deploying your projects across mulitple servers then employee class properties will be persisted and transferred across them.Because of Beans will be persisted and transferred across them.

Real time Scenario:

Java Beans are used throughout JAVA EE as a universal Contract. Java Server page(JSP) uses Java Beans as data transfer objects between pages or between servlets and Jsp's. Another example,Java Beans are are used for Integration Support for MIME data types into Java EE. 

To access all get and set the values of private variables(properties)we use public getter and setter methods as shown in the above example.


1 comment:

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...