Bean Internals  «Prev  Next»
Lesson 17Using JavaBean properties
ObjectiveLearn how to use a JavaBean property.

Using JavaBean Properties

To understand how properties are used, it is necessary to realize the different scenarios in which properties are important.
Every situation involving the use of properties can be simplified to simple accessor method calls.
Following are some of the scenarios in which Bean properties reveal themselves:
  1. Properties are accessed programmatically via public accessor methods.
  2. Properties are accessed visually via property sheets in application builder tools.
  3. Properties appear as object fields in scripting environments such as JavaScript or VBScript.
  4. Properties are used to persistently store and retrieve the state of a Bean.


Properties in Scripting Environments

Scripting environments such as JavaScript, VBScript, Python, and Perl offer a powerful means of interacting with Beans and using them directly in Web pages. One of the key ways Beans expose themselves to scripting environments is through properties.
Properties are accessible to scripts as member variables of Bean objects. The scripting environment is accessing properties through accessor methods behind the scenes.

To define a property in a bean class, supply public getter and setter methods. For example, the following methods define an int property called mouthWidth:
public class FaceBean {
 private int mMouthWidth = 90;
 public int getMouthWidth() {
  return mMouthWidth;
 }
 public void setMouthWidth(int mw) {
  mMouthWidth = mw;
 }
}

A builder tool like NetBeans recognizes the method names and shows the mouthWidth property in its list of properties. It also recognizes the type, int, and provides an appropriate editor so the property can be manipulated at design time. This example shows a property than can be read and written. Other combinations are also possible. A read-only property, for example, has a getter method but no setter. A write-only property has a setter method only. A special case for boolean properties allows the accessor method to be defined using is instead of get. For example, the accessor for a boolean property running could be as follows:

public boolean isRunning() {
    // ...
}

The next lesson concludes this module.
In it, you review what you covered up to this point, and end with a short quiz.

Create Exercise - Properties

Click the Exercise link below to create a property and explain how it is used.
Create Exercise - Properties

SEMrush Software