Accessor Methods

Accessor Methods

Concept of Accessor Methods

  • Accessor methods enable other objects to retrieve values of instance variables in a secure way.
  • They are also known as getters because they get the attribute values.

Reason to Use Accessor Methods

  • Accessor methods promote encapsulation, one of the major principles of Object Oriented Programming (OOP).
  • They hide the internal details of a class, providing a way to limit the access to the internal data.

Basic Structure of Accessor Methods

  • The method name often starts with ‘get’ followed by the variable name.
  • It typically is a public method and returns the value of the private attribute, enabling controlled access.

Accessor Method in Action

  • Consider a class named ‘Rectangle’ with a private attribute ‘length’.
  • An accessor method to get the ‘length’ will be written as:
    public class Rectangle {
      private double length;
    
      public double getLength() {
          return length;
      }
    }
    
  • The above accessor method ‘getLength’ retrieves the value of ‘length’ attribute.

Role in Application Building

  • Accessor methods are crucial in building real-world applications where certain attributes or properties need to be kept private.
  • They allow developers to maintain strict control over how and when data can be accessed.

Java Specifics

  • In Java, it’s standard practice to declare instance variables as private and provide accessor methods for them.

Best Practices

  • Avoid any side effects in accessor methods.
  • Preferably, they should only return the value of the attribute, without altering any state.