Encapsulation and Accessor Methods in Java

Encapsulation and Accessor Methods in Java

In the world of object-oriented programming, encapsulation is one of the fundamental pillars. It is a concept that allows you to hide the internal representation of an object, that is, its data, exposing only the operations (methods) that are allowed to be performed with that data. In Java, encapsulation is achieved through the use of access modifiers such as private, protected, public, and default code> (without modifier), and the implementation of accessor methods, known as getters and setters.

Why Encapsulate?

Encapsulating an object means protecting its members (attributes and methods) from improper or unexpected access. This is important for several reasons:

  • Access Control: Allows access to object data to be controlled, so that only specific methods can read or modify that data.
  • Flexibility and Maintainability: By hiding the implementation details, you can change the internal code without affecting other places in the system that use the object.
  • Security: Prevents the internal state of the object from being changed in an inappropriate or unexpected way, ensuring data integrity.

Access Modifiers

In Java, access modifiers define the visibility level of an attribute, method, or class. Are they:

  • private: The member can only be accessed within the class itself.
  • default: The member can be accessed by any class in the same package.
  • protected: The member can be accessed in the same package or by subclasses in different packages.
  • public: The member can be accessed from anywhere.

Getters and Setters

getters and setters are methods that serve, respectively, to obtain and set the value of an attribute of an object. They are the basis of encapsulation in Java, as they allow you to implement access control logic to the private attributes of a class.

A getter is a public method that returns the value of a private attribute, while a setter is a public method that allows you to set the value of that attribute. When using setters, it is possible to include validations and business rules, ensuring that only valid values ​​are assigned to attributes.

Practical example

Let's consider a class Person that has a private attribute age. To allow access to this attribute, we use a getter and a setter:

public class Person {
   private int age;

   public int getAge() {
      return age;
   }

   public void setAge(int newAge) {
      if (newAge >= 0) {
         age = newAge;
      } else {
         System.out.println("Invalid age!");
      }
   }
}

In the example above, the setAge method includes a check to ensure that the age is not negative. This is an example of how setters can be used to validate data before modifying it.

Good Practices

When implementing getters and setters, there are some best practices that should be followed:

  • Name the methods clearly and consistently, using the pattern getAttributeName and setAttributeName.
  • Use setters to validate data before assigning it to attributes.
  • Consider using getters and setters even when validation is not required, to maintain consistency and the possibility of adding validations in the future.
  • Avoid setters in classes that represent immutable objects.

Conclusion

Encapsulation and the use of getters and setters are fundamental in object-oriented programming in Java. They allow you to control access to an object's data, protect data integrity, and facilitate code maintenance. By adopting these practices, developers can create systems that are more robust, secure, and easier to maintain.

Now answer the exercise about the content:

What is the purpose of the `setIdade` method in the `Pessoa` class according to the practical example presented in the text on Encapsulation and Accessor Methods in Java?

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

You missed! Try again.

Article image Encapsulation and accessor methods (getters and setters): Encapsulation in different programming languages

Next page of the Free Ebook:

82Encapsulation and accessor methods (getters and setters): Encapsulation in different programming languages

7 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