What You Need to Know about JavaBeans
A JavaBean is a special type of Java class that you can use in several interesting ways to simplify program development. Some beans are designed to be visual components that you can use in a graphic user interface (GUI) editor to build user interfaces quickly. Simply put, a JavaBean is any Java class that conforms to the following rules:
- It must have an empty constructor — that is, a constructor that accepts no parameters. If the class doesn’t have any constructors at all, it qualifies because the default constructor has no parameters. But if the class has at least one constructor that accepts one or more parameters, it must also have a constructor that has no parameters to qualify as a JavaBean.
- It must have no
publicinstance variables. All the instance variables defined by the class must be either
- It must provide methods named
setPropertyto get and set the value of any properties the class provides, except for
booleanproperties that use
isProperty to get the property value. The term property isn’t an official Java term. In a nutshell (or should that be in a beanpod?), a property is any value of an object that can be retrieved by a get method (or an
ismethod, if the property is
boolean) or set with a
setmethod. If a class has a property named
lastName, for example, it should use a method named
getLastNameto get the last name and
setLastNameto set the last name. Or, if the class has a
taxable, the method to set it is called
setTaxable, and the method to retrieve it is
Note that a class doesn’t have to have any properties to be a JavaBean, but if it does, the properties have to be accessed according to this naming pattern. Also, not all properties must have both a
get and a
set accessor. A read-only property can have just a
get accessor, and a write-only property can have just a
The property name is capitalized in the methods that access it, but the property name itself isn’t. Thus
setAddress sets a property named
That’s all there is to it. More advanced beans can also have other characteristics that give them a visual interface so that they can be used drag-and-drop style in an integrated development environment (IDE). Also, some beans implement an interface that allows their state to be written to an output stream so that they can be re-created later. But those features are optional; any class that meets the three criteria stated here is a bean and can be used as a bean in JSP pages.
You’ve already seen plenty of classes that have methods with names like
setStatus. These names are part of a design pattern called the Accessor pattern. Thus you’ve seen many examples of beans throughout this book, and you’ve probably written many bean classes yourself already.
Any class that conforms to this pattern is a bean. There’s no
JavaBean class that you have to extend; neither is there a
Bean interface that you have to implement to create a bean. All a class has to do to be a bean is stick to the pattern.