Bean Internals  «Prev  Next»
Lesson 8Defining accessor methods
ObjectiveLearn how to access properties using accessor methods.

Defining JavaBeans Accessor Methods

The following getter and setter methods provide access to an integer Bean property named count:

public intgetCount();
public voidsetCount(int c);

The first method is the getter method, which is evident by the fact that it is returning (getting) an integer value.
The second method is the setter method, and returns a void value but accepts an integer value as its only argument.
Notice that the methods are named
getCount() and
setCount(), 

to clearly signify their purpose.
You should note that properties aren't required to always have pairs of accessor methods.
It is perfectly acceptable for a property to have only a getter method, for example, in which case the property would be read-only. Likewise, it is possible, although less likely, to make a property write-only by providing a setter method and no getter method.

Accessor methods are getter() methods

Properties are always accessed via method calls on their owning object. For readable properties there will be a getter method to read the property value. For writable properties there will be a setter method to allow the property value to be updated. Thus even when a script writer types in something such as "b.Label = foo" there is still a method call into the target object to set the property, and the target object has full programmatic control.
So properties need not just be simple data fields, they can actually be computed values. Updates may have various programmatic side effects. For example, changing a bean's background color property might also cause the bean to be repainted with the new color. For simple properties the accessor type signatures are:
void setFoo(PropertyType value); // simple setter
PropertyType getFoo(); // simple getter
GetFoo and setFoo are simply example names. Accessor methods can have arbitrary names.
In the next lesson, techniques to access properties using accessor methods will be discussed.

Accessor methods - Exercise

Click the Exercise link below to define a pair of accessor methods.
Accessor Methods - Exercise
In the next lesson, indexed properties will be discussed.