Java Encapsulation

Java Encapsulation

Encapsulation, one of the four fundamental OOP concepts, is the mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit.

The main purpose of encapsulation is to ensure data hiding. To achieve this, you must:

  1. Declare the variables of a class as private.
  2. Provide public "setter" and "getter" methods to modify and view the variables' values.

Why Encapsulation?


Getters and Setters

To access the private variables, we use public "get" and "set" methods.

By convention, getters start with get and setters start with set, followed by the variable name (e.g., getName(), setName()).

Encapsulation with Getters and Setters

public class Person {
  private String name; // private = restricted access

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

// Setter public void setName(String newName) { // We can add validation logic here if (newName != null && !newName.isEmpty()) { this.name = newName; } } }

public class Main { public static void main(String[] args) { Person myObj = new Person(); // myObj.name = "John"; // This would cause an error myObj.setName("John"); // Set the value of the name variable to "John" System.out.println(myObj.getName()); } }

In the setName method, we added a simple validation check. This is a key benefit of encapsulation: you control how your data is set, preventing invalid data from being assigned to your object's attributes.