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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.