What are the Java Bean conventions?

QuestionsQuestions8 SkillsProJava POJO ClassOct, 25 2025
0136

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:

  1. Public No-Argument Constructor: A Java Bean must have a public no-argument constructor, allowing for easy instantiation.

  2. Properties: Properties of a Java Bean are typically private fields. These fields can be accessed and modified through public getter and setter methods.

  3. Getter and Setter Methods:

    • For a property named propertyName, the getter method should be named getPropertyName() and return the property's value.
    • The setter method should be named setPropertyName(propertyType value) and set the property's value.
  4. Serializable: A Java Bean should implement the Serializable interface to allow its instances to be serialized.

  5. Event Handling: Java Beans can support event handling by allowing listeners to be added and removed, typically through methods like addPropertyChangeListener and removePropertyChangeListener.

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.

0 Comments

no data
Be the first to share your comment!