Sobes.tech
Junior — Middle

Explain the meaning and main function of encapsulation in object-oriented programming.

sobes.tech AI

Answer from AI

Encapsulation is a principle of object-oriented programming that involves combining data (variables) and methods that work with this data into a single object, as well as hiding the internal implementation of the object from the outside world.

The main function of encapsulation is to protect the internal state of an object from direct access and modification from outside, providing a controlled interface through methods (getters and setters). This enhances security, simplifies maintenance, and allows changing the internal implementation without affecting external code.

Example in Java:

public class Person {
    private String name; // hidden field

    public String getName() { // controlled access
        return name;
    }

    public void setName(String name) {
        if(name != null && !name.isEmpty()) {
            this.name = name;
        }
    }
}

Here, the name field is not directly accessible, which prevents incorrect assignment.