Java Bean Properties

Bean properties refer to the variables or data members of a Java Bean class. These classes are accessed and manipulated using getter and setter methods. A Java Bean is a class that follows a set of conventions. It is designed to be reusable in different contexts. We can use Java Bean in graphical user interfaces or in database access.

In a Java Bean class, properties are defined as private instance variables and are accessed using public methods. These methods are also known as accessor methods. The accessor method that retrieves the value of a property is called a getter method. The accessor method that sets the value of a property is called a setter method.

The naming convention for getter and setter methods is standard, with the getter method named with the prefix get followed by the property name, and the setter method named with the prefix set followed by the property name. For example, a bean property named firstName would have a getter method named getFirstName() and a setter method named setFirstName(String firstName).

By using bean properties, other classes can access and manipulate the state of a Java Bean object without exposing the implementation details of the class. This encapsulation is a key aspect of object-oriented programming and helps to improve the maintainability and reusability of code.

Let’s take an example of the following code to understand the properties in Java Bean.

Example:

public class Person {
    private String name;
    private int age;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
}

In the example above, the class Person has two private instance variables, name and age. The class also has four public methods, two getter methods getName() and getAge() and two setter methods setName(String name) and setAge(int age).

The getter methods simply return the value of their corresponding property. While the setter methods set the value of the property to the specified input parameter. For example, if we create a Person object and want to set the name property to Sajan and the age property to 30, we can call the corresponding setter methods like this:

Person person = new Person();
person.setName("Sajan");
person.setAge(30);

Then we can retrieve the values of the properties using the corresponding getter methods like this:

String name = person.getName();
int age = person.getAge();

In this post, we learned a simple way of using Java Bean properties that makes us understand this concept easily.

Sharing Is Caring: