Bean Internals  «Prev  Next»
Lesson 6Accessor methods
ObjectiveLearn about accessor methods.

JavaBeans Accessor Methods

JavaBeans property access is managed through a very simple and straightforward technique: accessor methods.
An accessor method[1] is a public method defined in a Bean that enables access to the value of a particular property. Accessor methods typically come in pairs, with one half of the pair capable of reading a property value and the other half capable of writing a property value. A pair of accessor methods is all that is required to have full access to a Bean property.
  • Javabeans Accessors: Accessors are a key element to proper encapsulation.
    They can restrict access to only read/write data, inform other objects of changes to data, and perform validation on new values being set. Consistent accessor usage makes class modification easy and transparent.
    An accessor is a method that allows read or write access to a section of a class or instance data. These are commonly defined using the naming convention
    1. getVarName(): reads the data for class/instance variable varName
    2. setVarName(value): sets the value for class/instance variable varName
    By providing and using accessor methods to read/write data contained within a class, you provide stronger encapsulation for the data of that class. This has several advantages, especially if you decide to change the implementation of the underlying data (or remove the data itself and replace it with a computation). In addition, creating accessors for a private class/instance variable allow you to restrict access to read-only or write-only by providing only a get or set method. The new HotSpot VM provides run-time optimization and part of this optimization is automatic inlining of simple methods. If you write accessors that just set and return a value, these will be inlined to simple assignment statements.


Role of "accessor methods" within the context of JavaBeans

In the context of JavaBeans, accessor methods (also known as getters and setters) play a crucial role in encapsulating an object's properties while allowing controlled access to them. JavaBeans are reusable software components that follow specific conventions, and accessor methods are a key part of these conventions.
Here’s the role of accessor methods in JavaBeans:
  1. Encapsulation of Properties: JavaBeans typically have private instance variables (properties) that are accessed indirectly through public accessor methods. This adheres to the principle of encapsulation, where the internal state of the object is hidden and can only be accessed or modified through these methods.
  2. Standard Naming Conventions:
    • Accessor methods in JavaBeans follow a strict naming convention:
      • Getters: Methods used to retrieve the value of a property. The method name starts with `get` followed by the property name with the first letter capitalized. For example, for a property `name`, the getter would be `getName()`.
      • Setters: Methods used to modify the value of a property. The method name starts with `set` followed by the property name with the first letter capitalized. For example, for a property `name`, the setter would be `setName(String name)`.
  3. Compliance with JavaBeans Specification: For a class to be considered a JavaBean, it must adhere to the JavaBeans specification, which includes the presence of public getter and setter methods for each property. This allows tools and frameworks to automatically recognize, introspect, and manipulate JavaBeans properties.
  4. Interoperability with IDEs and Frameworks: Many frameworks and IDEs, such as JavaBeans-aware development tools (like IDEs), rely on these accessor methods to generate user interfaces, data-binding mechanisms, or manage components. The standardized method names allow tools to identify which properties a bean exposes.
  5. Property Change Events: In more advanced JavaBeans, accessor methods can be used to trigger property change events when a setter method is called. This is useful for notifying other components that a bean’s property has been updated, often used in graphical user interfaces (GUIs) or in Java Enterprise applications.


Example of Accessor Methods in a JavaBean:
public class PersonBean implements java.io.Serializable {
    private String name;
    private int age;

    // Getter for name
    public String getName() {
        return name;
    }

    // Setter for name
    public void setName(String name) {
        this.name = name;
    }

    // Getter for age
    public int getAge() {
        return age;
    }

    // Setter for age
    public void setAge(int age) {
        this.age = age;
    }
}

In this example, the `PersonBean` class uses accessor methods to encapsulate and expose the `name` and `age` properties, in line with the JavaBeans conventions.
In summary, accessor methods are fundamental to the design of JavaBeans because they allow controlled access to the properties of a bean, adhere to naming conventions that enable interoperability with various tools and frameworks, and support encapsulation.


Data defined in the Class must be private

Making instance variables non-private allows another class to change their values without the owner of that data knowing about the change. If the owner does not know about the change:
  1. the owner has no control over the value; it could be outside the intended range of the data
  2. the owner cannot know the value has change, and cannot respond if needed
  3. the owner cannot tell others that the value has changed
  4. the owner cannot allow others to veto the change
If you ever decide to change your code to allow other classes to listen for changes, or restrict bounds on a variable, you would need to find every reference to the data and change each variable. This can be very painful if the class were a public library that many people had used in their own code.
In addition, you cannot change the implementation of the data without changing the users of that data. For example, suppose you had an integer instance variable to keep track of an 'ID' for a list node. Perhaps you had done some research and decided that the memory cost of keeping that ID was more expensive than recomputing it the few times it was needed.
If ID were only available by means of an accessor, all you would need to do to affect the change is to
  1. remove the instance variable and
  2. change the getID accessor to compute the ID and
  3. return it.
This is far simpler than creating the getID accessor and going back and changing every reference to x.id. Privacy is the key to encapsulation and all manipulation of an object's state must be done by the object itself. Once you use accessors to read/write class/instance data, that data is instantly available as a JavaBean property.
In the next lesson, Getter and Setter methods will be discussed.

[1] Accessor method: A public method defined in a Bean that reads or writes the value of a property.

SEMrush Software