JavaBeans Naming Conventions

As I mentioned earlier, a Java bean is a class that has a no-argument constructor and conforms to the JavaBeans naming conventions. The bean properties are accessed through getter and setter methods, collectively known as a bean’s accessor methods. Getter and setter method names are composed of the word get or set, respectively, plus the property name with the first character of each word capitalized. A regular getter method has no parameters but returns a value of the property’s type, while a setter method has a single parameter of the property’s type and has a void return type. Here’s an example:

public class CustomerBean implements java.io.Serializable {
  
    String firstName;
    String lastName;
    int accountNumber;
    int[] categories;
    boolean preferred;
  
    public String getFirstName(  ) {
      return firstName;
    }
  
    public void setFirstName(String firstName) {
      this.firstName = firstName;
    }

A readable property has a getter method; a writable property has a setter method. Depending on the combination of getter and setter methods, a property is read-only, write-only, or read/write. Note that it’s the presence of the accessor methods that defines the property; how the property value is represented inside the class makes no difference at all.

A read-only property doesn’t necessarily have to match an instance variable one-to-one. Instead, it can combine instance variable values, or any values, and return a computed value:

public String getFullName( ) { return (new StringBuffer(firstName).append(" ...

Get JavaServer Pages, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.