Java Beans

 

JavaBeans standards were developed as a guideline for developers to write clear and easy to follow classes. Classes that do not follow JavaBeans standards still compile but they are harder to read and use for other developers.

A JavaBean is a Java class which has instance variables. These instance variables are referred to as properties of the class. Encapsulation principle of Object-Oriented Programming allows private instance variables of a Java class to be accessed only through public methods. JavaBeans standards defines the following categories for such methods:

setter methods: public methods that are used to change the value of a private member variable.

getter methods: public methods that are used to get the value of a private member variable.

JavaBeans standards allow access to private methods only through setter and getter methods and defines the following rules for them.

-A JavaBean’s properties start with a lowercase letter, following Lower CamelCase notation.

– The first word in a setter method’s name is set. Following Lower CamelCase notation, a setter method takes the form set<Property name starting with uppercase>.

For example, setWidth for property width, setHeight for property height.

– The first word in a getter method’s name is get. Following Lower CamelCase notation, a setter method takes the form get<Property name starting with uppercase>.

For example, getWidth() for property width, getHeight for property height.

– For boolean properties, the first word for the getter method is is. Following Lower CamelCase notation, the getter method for a boolean property gets either the form is<Property name starting with uppercase> or get<Property name starting with uppercase>. Both are legal

For example, isRunning() or getRunning() for boolean property running.

– setter methods are public with return type void. A setter method has one argument that is the same as the property’s argument. In the body of the setter method, the argument’s value is set to the property’s value.

– getter methods are public with return type same as the property’s type and no arguments. The body of the method returns the property’s value.

Based on this, let’s write an example Java class that follows JavaBeans Naming Rules. We will write a class named Rectangle which has two properties: width and height.

public class Rectangle {

private int width;

private int height;

public int getWidth() {

return width;

}

public void setWidth(int width) {

this.width = width;

}

public int height() {

return height;

}

public void setHeight(int height) {

this.height = height;

}

}

%d bloggers like this: