What is a Java bean? How is it different from Java class?
A Java bean is a Java class that should follow the following conventions:
a. It should have a no argument constructor.
b. It should be serializable i.e. it must implement the java.io.Serializable interface. Serializability ensures that the object’s state can be written into streams such as files (called serialization) and can be restored later into object as well (called deserialization).
c. It should provide methods to set and get the values of the properties, known as getter and setter methods.
A Java bean is different from a Java class in the sense that a Java class definition does not have any restriction whereas a Java bean class definition has. Thus a Java bean class is just a Java class with the properties mentioned above. An example of a Java bean class is:
package bsccsit;
import java.io.Serializable;
public class JavaBeanClassEmployee implements Serializable {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now, to access this Java bean class (from another package), we should use its getter and setter methods as:
package seventhsemester;
import bsccsit.JavaBeanClassEmployee;
public class Test {
public static void main(String []args) {
JavaBeanClassEmployee e = new JavaBeanClassEmployee();
e.setId(1);
e.setName("Lok");
System.out.println(e.getId() + " " + e.getName());
}
}
Comments
Post a Comment