Sobes.tech
Junior — Middle

Can you explain what encapsulation is in object-oriented programming?

sobes.tech AI

Answer from AI

Encapsulation is a principle of object-oriented programming that involves hiding the internal implementation of an object and providing access to data only through specific methods (getters and setters). This helps protect data from direct modification and allows control over their state.

For example, a class may have a private field that cannot be accessed directly, but can be accessed through public methods:

public class User {
    private String password; // hidden field

    public void setPassword(String password) {
        // you can add password complexity checks here
        this.password = password;
    }

    public String getPassword() {
        return "****"; // do not return the real password
    }
}

Thus, encapsulation helps improve security and robustness against errors in the code.