Developing Java Beans public void set( value); public get(); The existence of a matching pair of methods that conform to this pattern represents a read/write property with the name of the type . If only the get() method exists, the property is considered to be read-only; if only the set() method exists, the property is considered to be write-only. If the is boolean, the get() method can be replaced or augmented with a method that uses the following signature: public boolean is(); Let’s look back at the Temperature class. The current temperature is stored within an object of type Temperature, but up until now we have not provided a way to access that value. So now we can add a read-only property called CurrentTemperature. The code for the Temperature class will now include the following: package BeansBook.Simulator; import java.util.Vector; public class Temperature { // the current temperature in Celsius protected double currentTemp = 22.2; [The rest of the existing code goes here] // the get method for property CurrentTemperature public double getCurrentTemperature() { return currentTemp; } } It is important to recognize that properties are not defined by data members of the object’s class. One reason for this is that it would break encapsulation. More importantly, properties can be computed when they are needed without having to be stored explicitly. In an earlier example we described a Thermometer class that tracked temperatures from two locations. We could define a property called NumberOfLocations. This is a read-only property that describes how many locations are being tracked by the thermometer. In this case we don’t need to explicitly store a data member for this property, we just know that the value is always 2. We could add a property get method to access this value, as follows: public int getNumberOfLocations() { return 2: } Although our thermometer isn’t a visual component yet, imagine that at some point it will be capable of displaying the temperature from one of its source thermometers. Let’s design the Thermometer so that it is capable of displaying temperatures in either Celsius or Fahrenheit. We call this property DisplayingCelsius, and we expose it using a boolean data type. Remember that this doesn’t refer to the way that the property is stored internally, only the way that the property is page 51
This entry was posted
on Friday, September 29th, 2006 at 3:27 pm and is filed under java.
You can follow any responses to this entry through the RSS 2.0 feed.
Responses are currently closed, but you can trackback from your own site.