12.3. Encapsulation and Accessor Methods (Getters and Setters)

Encapsulation is one of the four fundamental principles of object-oriented programming (OOP), alongside inheritance, polymorphism and abstraction. It is essential for creating secure, reliable, and easy-to-maintain software. Encapsulation in Java is implemented through the use of access modifiers and accessor methods, known as getters and setters.

Access Modifiers: private, protected, public

Access modifiers in Java define the visibility of a class, method, or variable in relation to other parts of the code. There are three main access modifiers:

  • private: The member is only accessible within the class itself. It is the most restrictive access level and is used to hide implementation details and maintain data integrity.
  • protected: The member is accessible within the class itself, in subclasses (even if they are in different packages) and in other classes of the same package. It is less restrictive than private and is commonly used in situations where there is inheritance.
  • public: The member is accessible from any other class, regardless of the package they are in. It is the least restrictive access level and should be used with caution as it exposes members to the outside world.

Encapsulation in Practice

Encapsulation is the practice of hiding the internal implementation details of a class and exposing only the methods necessary to use that class. This is done to avoid direct access to the fields (also known as instance variables) of a class, which could result in inconsistent or unwanted states. Instead, fields are marked private and accessed through public methods, getters and setters.

Getters and Setters

Getters and setters are public methods that allow reading (get) and modifying (set) private fields of a class. They are the input and output port for the encapsulated data. The convention in Java is to name these methods as getFieldName for getters and setFieldName for setters, where FieldName starts with a capital letter and corresponds to the name of the private field.

Example of Encapsulation with Getters and Setters


public class Person {
    private String name;
    private int age;

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

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

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

    // Setter for the age field
    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        } else {
            throw new IllegalArgumentException("Age must be greater than zero.");
        }
    }
}

In this example, the Person class has two private fields: name and age. The corresponding getters and setters methods allow controlled access to these fields. Note that in the setAge setter, there is a check to ensure that the age is not negative, which is an example of how encapsulation helps maintain data integrity.

Advantages of Encapsulation

Encapsulation offers several advantages, including:

  • Access control: Developers can control who has access to a class's instance variables.
  • Flexibility and maintenance: The internal implementation of a class can be changed without affecting the classes that use it, as long as the accessor methods remain the same.
  • Increased security: By avoiding direct access to fields, it is possible to prevent inconsistent states and protect data against unwanted manipulations.

Conclusion

Encapsulation is a fundamental concept in object-oriented programming that helps protect data and keep code organized and secure. The private, protected, and public access modifiers are powerful tools for controlling the visibility of members of a class. Getters and setters are the methods that allow you to interact with these members in a controlled manner, respecting business rules and maintaining data integrity. By understanding and correctly applying encapsulation, programmers can create systems that are robust and easy to maintain.

Now answer the exercise about the content:

Which of the following statements about encapsulation 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): Definition of accessor methods (getters)

Next page of the Free Ebook:

78Encapsulation and accessor methods (getters and setters): Definition of accessor methods (getters)

4 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