A JavaBean is a Java class. Like other Java classes, JavaBeans are reusable code. They are unique in their design because they encapsulate several objects into one. There are three conventions that a JavaBean class must follow:
- The constructor should not take any arguments
- It must be serializable
- It must contain mutator and accessor methods for its properties
Here is an example JavaBean class:
public class MyBean implements java.io.Serializable {
// instance variables
private int studentId;
private String studentName;
// no-argument constructor
public MyBean() {
}
// mutator/setter
public void setStudentId(int theID) {
this.studentId = theID;
}
// accessor/getter
public int getStudentId() {
return studentId;
}
// mutator/setter
public void setStudentName(String theName) {
this.studentName = theName;
}
// accessor/getter
public String getStudentName(){
return studentName;
}
}
Accessing JavaBean classes is as simple as using the mutator and accessor methods. This is likely not new to you, but there is a good chance you did not know that those carefully coded classes you created were called JavaBean classes.