Sobes.tech
Middle

What is encapsulation? What is its benefit?

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).

Benefits of encapsulation:

  • Protects data from incorrect usage and external modifications.
  • Simplifies maintenance and modification of code, as the internal implementation can be changed without affecting the external interface.
  • Improves readability and structure of the code.

Example in Java:

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

    public String getName() {
        return name;
    }

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