Design Patterns for Properties in a Java Bean

By: Sam Chen Viewed: 153438 times  Printer Friendly Format    


A property is a subset of a Bean's state. The values assigned to the properties determine the behavior and appearance of that component. This section discusses three types of properties: simple, Boolean, and indexed.

Simple Properties

A simple property has a single value. It can be identified by the following design patterns, where N is the name of the property and T is its type.

public T getN( );
public void setN(T arg);

A read/write property has both of these methods to access its values. A read-only property has only a get method. A write-only property has only a set method. The following listing shows a class that has three read/write simple properties:

public class Box {
 
private double depth, height, width;
public double getDepth( ) {
return depth;
}
public void setDepth(double d) {
depth = d;
}
public double getHeight( ) {
return height;
}
public void setHeight(double h) {
height = h;
}
public double getWidth( ) {
return width;
}
public void setWidth(double w) {
width = w;
}
}

Boolean Properties

A Boolean property has a value of true or false. It can be identified by the following design patterns, where N is the name of the property:

public boolean isN( );
public boolean getN( );
public void setN(boolean value);

Either the first or second pattern can be used to retrieve the value of a Boolean property. However, if a class has both of these methods, the first pattern is used. The following listing shows a class that has one Boolean property:

public class Line {
private boolean dotted = false;
public boolean isDotted( ) {
return dotted;
}
public void setDotted(boolean dotted) {
this.dotted = dotted;
}
}

Indexed Properties

An indexed property consists of multiple values. It can be identified by the following design patterns, where N is the name of the property and T is its type:

public T getN(int index);
public void setN(int index, T value);
public T[ ] getN( );
public void setN(T values[ ]);

The following listing shows a class that has one read/write indexed property:

public class PieChart {
private double data[ ];
public double getData(int index) {
return data[index];
}
public void setData(int index, double value) {
data[index] = value;
}
public double[ ] getData( ) {
return data;
}
public void setData(double[ ] values) {
data = new double[values.length];
System.arraycopy(values, 0, data, 0, values.length);
}
}



Most Viewed Articles (in Java Beans )

Latest Articles (in Java Beans)

Comment on this tutorial