In the previous example, the Person
class defined properties name
and age
, of types String
and int
respectively. The properties were defined by the fact that the class defined methods getName
, setName
, getAge
, and setAge
.
This method for defining properties is outlined in detail in the JavaBeans specification. However, the basic rules are as follows:
To define a configurable property, your class should define a
getX
method that takes no arguments and returns a value, and asetX
method that takes one argument and returnsvoid
. The type returned by thegetX
method must be the exact same type as the type taken as an argument by thesetX
method, and may be any Java type. Both thegetX
andsetX
methods must be declaredpublic
.An exception to the above rule is that the
getX
method for a Boolean property may be replaced byisX
. For example,getRunning
andisRunning
can both define therunning
property, but only ifrunning
is a Boolean property.The name of the property is formed by taking the part of the method name following the
get
orset
and changing the first letter to lower case. For example, the methodgetFirstName()
would define a property calledfirstName
.An exception to the above rule is if the first two letters following the
get
orset
are both capitalized. In such a case, no letters are changed to lower case. For example, thegetURL
method defines a property calledURL
.
It is important to pay attention to the capitalization, because property names are case-sensitive. For example, an entry Age=20
would not set the age
property of the Person
object.