java bean

java

In Java, a bean is a Java object that follows certain conventions for storing and manipulating data. Beans are often used to represent data in a Java application, such as the data in a database table or the state of a user interface.

Beans typically follow the JavaBeans specification, which defines a set of conventions for naming and accessing the properties of a bean. According to the specification, a bean should have:

  • A default constructor, which is a constructor with no arguments.
  • A set of getter and setter methods for each property, which follow a naming convention such as getProperty() and setProperty().
  • A toString() method that returns a string representation of the bean.

Here is an example of a simple bean in Java:

public class User {
  private String name;
  private int age;

  // Default constructor
  public User() {}

  // Constructor with arguments
  public User(String name, int age) {
    this.name = name;
    this.age = age;
  }

  // Getter and setter methods for the name property
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  // Getter and setter methods for the age property
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }

  // toString method
  @Override
  public String toString() {
    return "User{" +
           "name='" + name + '\'' +
           ", age=" + age +
           '}';
  }
}

This bean represents a user with a name and an age, and it has getter and setter methods for these properties. It also has a default constructor and a constructor with arguments, and a toString() method that returns a string representation of the bean.

For more information on beans and the JavaBeans specification, you can refer to the Java documentation: