12.8 Encapsulation and Accessor Methods (Getters and Setters): Encapsulation in Different Programming Languages

Encapsulation is one of the four fundamental pillars of Object Oriented Programming (OOP), along with inheritance, abstraction and polymorphism. Encapsulation is the principle that allows you to hide the internal details of how an object works, exposing only the safe and necessary operations for interacting with that object. This is done by controlling access to a class's internal variables and methods, making some members private and others public.

Accessor methods, known as getters and setters, are the most common way to implement encapsulation in many programming languages. They are public methods that allow reading (getters) and writing (setters) private properties of a class. Through them, it is possible to validate and control the values ​​that are being assigned to variables, maintaining the integrity and consistency of the object's internal state.

Encapsulation in Java

In Java, encapsulation is implemented using access modifiers: private, protected, public and default (no modifier). Typically, instance variables are defined as private, which means they cannot be accessed directly from outside the class. To allow access to these variables, getters and setters methods are used.


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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }
}

In this example, the setAge method includes validation to ensure that age is not a negative value. This illustrates how setters can be used to enforce business rules and maintain object integrity.

Encapsulation in C#

C# is another object-oriented language that supports encapsulation in a similar way to Java. However, C# offers a leaner syntax for declaring properties with automatic getters and setters, known as self-implemented properties.


public class Person {
    public string Name { get; set; }
    public int Age {
        get { return age; }
        set { age = value > 0 ? value : age; }
    }
    private int age;
}

In this example, the Name property is a self-implemented property that automatically creates an underlying private field. The Age property has custom logic in the setter to ensure age is not negative.

Encapsulation in Python

Python does not have explicit access modifiers like Java or C#. Instead, the convention is to use an underscore (_) before the name of an attribute to indicate that it should be treated as private. Although this does not prevent direct access to the attribute, it is a signal to other developers that the attribute is intended for use internal to the class. getters and setters methods in Python are often implemented using decorators @property, @attributo.setter, and @atributo.deleter.


class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

    @property
    def age(self):
        return self._age

    @idade.setter
    def age(self, value):
        if value > 0:
            self._age = value

The @property and @name.setter decorators allow you to define methods that behave like normal attributes, but with additional logic for reading and writing.

JavaScript Encapsulation

JavaScript traditionally did not support encapsulation natively, but with the introduction of classes in ECMAScript 2015 (ES6), this changed. Still, private fields are a more recent addition to the language and are denoted by a hash (#) before the field name.


class Person {
    #name;
    #age;

    constructor(name, age) {
        this.#name = name;
        this.#age = age;
    }

    get name() {
        return this.#name;
    }

    set name(value) {
        this.#name = value;
    }

    get age() {
        return this.#age;
    }

    set age(value) {
        if (value > 0) {
            this.#age = value;
        }
    }
}

The get and set methods work like getters and setters and allow controlled access to private fields.

Conclusion

Encapsulation is an essential practice for creating robust, secure, and easy-to-maintain software. Although programming languages ​​may vary in their specific approaches to implementing encapsulation, the underlying concept remains the same. The accessor methods getters and setters are powerful tools that allow developers to protect the internal state of objects and expose a clean and understandable interface to users of these classes. By mastering encapsulation and proper use of accessor methods, programmers can ensure their code is more reliable and maintainable in the long term.

Now answer the exercise about the content:

Which of the following correctly states the use of encapsulation in object-oriented programming languages?

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

You missed! Try again.

Article image Encapsulation and accessor methods (getters and setters): Object-oriented programming principles related to encapsulation

Next page of the Free Ebook:

83Encapsulation and accessor methods (getters and setters): Object-oriented programming principles related to encapsulation

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