Properties are discrete, named attributes of a Java bean that can affect its appearance or behavior. They are often data fields of a bean. For example, the JButton component has a property named text that represents the text to be displayed on the button. Private data fields are often used to hide specific implementations from the user and prevent the user from accidentally corrupting the properties. Accessor and mutator methods are provided instead to let the user read and write the properties.
The bean property-naming pattern is a convention of the JavaBeans component model that simplifies the bean developer's task of presenting properties. A property can be a primitive data type or an object type. The property type dictates the signature of the accessor and mutator methods.
In general, the accessor method is named get<PropertyName>() , which takes no parameters and returns a primitive type value or an object of a type identical to the property type. For example,
public String getMessage() { } public int getXCoordinate() { } public int getYCoordinate() { }
For a property of boolean type, the accessor method should be named is<PropertyName>() , which returns a boolean value. For example,
public boolean isCentered() { }
The mutator method should be named set<PropertyName>(dataType p) , which takes a single parameter identical to the property type and returns void . For example,
public void setMessage(String s) { } public void setXCoordinate( int x) { } public void setYCoordinate( int y) { } public void setCentered( boolean centered) { }
Note
You may have multiple get and set methods, but there must be one get or set method with a signature conforming to the naming patterns. |
Properties describe the state of the bean. Naturally, data fields are used to store properties. However, a bean property is not necessarily a data field. For example, in the MessagePanel class in §13.11, "Case Study: The MessagePanel Class," you may create a new property named messageLength that represents the number of characters in message . The get method for the property may be defined as follows :
public int getMessageLength() { return message.length(); }
Note
A property may be read-only with a get method but no set method, or write-only with a set method but no get method. |