Java Bean conventions are a set of guidelines that define how to create Java classes that follow the JavaBeans specification. Here are the key conventions:
-
Public No-Argument Constructor: A Java Bean must have a public no-argument constructor, allowing for easy instantiation.
-
Properties: Properties of a Java Bean are typically private fields. These fields can be accessed and modified through public getter and setter methods.
-
Getter and Setter Methods:
- For a property named
propertyName, the getter method should be namedgetPropertyName()and return the property's value. - The setter method should be named
setPropertyName(propertyType value)and set the property's value.
- For a property named
-
Serializable: A Java Bean should implement the
Serializableinterface to allow its instances to be serialized. -
Event Handling: Java Beans can support event handling by allowing listeners to be added and removed, typically through methods like
addPropertyChangeListenerandremovePropertyChangeListener.
Here’s a simple example of a Java Bean:
import java.io.Serializable;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class Person implements Serializable {
private String name;
private int age;
private PropertyChangeSupport support;
public Person() {
support = new PropertyChangeSupport(this);
}
public String getName() {
return name;
}
public void setName(String name) {
String oldName = this.name;
this.name = name;
support.firePropertyChange("name", oldName, name);
}
public int getAge() {
return age;
}
public void setAge(int age) {
int oldAge = this.age;
this.age = age;
support.firePropertyChange("age", oldAge, age);
}
public void addPropertyChangeListener(PropertyChangeListener pcl) {
support.addPropertyChangeListener(pcl);
}
public void removePropertyChangeListener(PropertyChangeListener pcl) {
support.removePropertyChangeListener(pcl);
}
}
This example demonstrates the conventions of a Java Bean, including private properties, public getter and setter methods, and support for property change listeners.
