12. Encapsulation and Accessor Methods (Getters and Setters)

The concept of encapsulation is one of the fundamental pillars of object-oriented programming (OOP), being essential for creating robust, secure and easy-to-maintain software. Encapsulation, in essence, is the practice of hiding the internal details of a class, exposing only what is necessary for external use. This is done by controlling access to members (attributes and methods) of the class.

In Java, encapsulation is achieved through the use of access modifiers, which are: private, protected, public and the default (no modifier). Choosing which modifier to use defines how class members can be accessed.

The private modifier is the most restrictive and is the key to effective encapsulation. When an attribute is marked as private, it cannot be accessed directly from outside the class, which prevents the object's internal state from being modified in unexpected or inappropriate ways.

But then, how do we access and modify these private attributes? This is where accessor methods come in, better known as getters and setters. These are public methods that allow the reading (getters) and modification (setters) of the values ​​of private attributes, in a controlled way.

Getters

A getter method, or simply getter, is a public method that returns the value of a private attribute. The method name usually starts with get followed by the attribute name with the first letter capitalized. For example, if we have a private attribute called name, the corresponding getter would be getName().

public class Person {
    private String name;
    
    public String getName() {
        return name;
    }
}

Getters are important because they allow other objects to read the state of an object without changing it. Additionally, they can provide a layer of abstraction; for example, if the way the name is stored changes in the future, the getter can be adjusted without affecting external code.

Setters

A setter method, or simply setter, is a public method that allows you to change the value of a private attribute. The method name usually starts with set followed by the attribute name with the first letter capitalized. Following the previous example, the setter for the name attribute would be setNome(String name).

public class Person {
    private String name;
    
    public void setName(String name) {
        this.name = name;
    }
}

Setters are essential for maintaining control over how private attributes are modified. They can include validation logic to ensure that only acceptable values ​​are assigned to attributes. For example, we may want to ensure that the name is not null or empty before assigning it to the attribute:

public void setName(String name) {
    if(name != null && !name.isEmpty()) {
        this.name = name;
    } else {
        throw new IllegalArgumentException("Name cannot be null or empty.");
    }
}

This approach ensures that the object always maintains a valid state, protecting data integrity and preventing unexpected behavior in the program.

Benefits of Encapsulation

Encapsulation brings several benefits, including:

  • Access Control: Allows the developer to restrict access to class members, protecting the internal state of the object.
  • Flexibility and Maintenance: As data access is done through methods, it is easier to modify the internal implementation without affecting the parts of the code that use the class.
  • Security: Prevents the object from being placed in an inconsistent state, as validation can be done in the setters.
  • Abstraction: Implementation details are hidden, exposing only what is necessary to use the class.

In summary, encapsulation and proper use of getters and setters are fundamental to creating Java classes that are safe, reliable, and easy to maintain. By following these practices, developers can create more robust, less error-prone systems.

It is important to note that although getters and setters are common practice, they should not be used interchangeably. In some cases, it may be preferable to use other methods to manipulate object state, especially if direct access to attributes is not necessary or if the business logic is complex. Each situation must be evaluated individually to determine the best approach.

In conclusion, encapsulation, along with getters and setters accessor methods, are key concepts in programming.object-oriented action in Java. They allow developers to build classes with well-defined interfaces that protect the integrity of internal data, contributing to the creation of more stable and reliable systems.

Now answer the exercise about the content:

_Which of the following statements about encapsulation and accessor methods in Java is correct?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Encapsulation and accessor methods (getters and setters): Encapsulation concept

Next page of the Free Ebook:

75Encapsulation and accessor methods (getters and setters): Encapsulation concept

5 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text