Encapsulation in Java: Getters and Setters

Encapsulation in Java: Getters and Setters

Encapsulation is one of the four fundamental pillars of object-oriented programming (OOP), along with inheritance, polymorphism and abstraction. In Java, encapsulation is a way to protect and control access to an object's data. The idea is that an object should have full control over how its information is accessed or modified, and this is done through the use of getter and setter methods.

What are Getters and Setters?

Getters and Setters are public methods that serve, respectively, to obtain (get) or set (set) the value of a private variable of a class. The use of getters and setters allows access to data in a controlled manner, enabling, for example, data validation before being assigned to a variable.

Why use Getters and Setters?

  • Data Hiding: You can hide the internal implementation details of the class and expose only the methods necessary for external use.
  • Validation: When defining a value, you can include validation logic to ensure the data is correct.
  • Flexibility: If the way data is stored changes, you can keep the same public interface, which means the code using the class doesn't need to change.

Example of Encapsulation with Getters and Setters

Let's consider a class Person that has two private attributes: name and age. The encapsulation of these attributes is done through the implementation of getters and setters methods.


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

    // Class constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

    // Setter for the 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) {
        if (age > 0) {
            this.age = age;
        } else {
            System.out.println("Invalid age!");
        }
    }
}

In the example above, the setName and setAge methods are responsible for setting the values ​​of name and age , respectively. The setAge method contains a simple validation to ensure that age is not a negative value.

Good Practices When Using Getters and Setters

  • The names of getters and setters methods must follow the Java naming standard, starting with get followed by the attribute name with the first letter capitalized for getters, and set followed by the attribute name with the first letter capitalized for setters.
  • Getters must be read-only methods, that is, they must not modify the state of the object.
  • Setters can include validation logic to ensure data is correct before it is assigned to attributes.
  • Consider making attributes immutable that do not need to be changed after the object is created. This is done by not providing setter methods for these attributes.

Final Considerations

Encapsulation is an essential technique in object-oriented programming, and the correct implementation of getters and setters is one of the means to achieve it. By encapsulating a class's data, you increase the security and robustness of your code, facilitate maintenance, and promote a clear and consistent interface for the class's users.

Although the use of getters and setters is common practice, it is important to remember that they are not a universal solution. In some cases, it may be more appropriate to use other methods or design patterns to access and modify an object's data. However, for most situations, especially for those learning Java and OOP concepts, understanding and correctly applying getters and setters is a fundamental step in software development.

With this knowledge in hand, you are now better prepared to create well-encapsulated and safe Java classes, following the best object-oriented programming practices.

Now answer the exercise about the content:

_Which of the following is NOT a good practice when using getters and setters in Java, according to the text provided?

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

You missed! Try again.

Article image Java Basic Syntax: Inheritance

Next page of the Free Ebook:

14Java Basic Syntax: Inheritance

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