How encapsulation protects private data if you can eventually access it through public methods?

Viewed 38

I have studied a lot to understand this but I can't understand the use of encapsulation.

Example

In the following example name is a private variable where using getters and setters you can assign values:

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

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

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

Here a name is passed using the public variables:

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

The question is:

What's the point of hiding the variable inside a class by making it private and then making it accessible with getter and setter public methods?

0 Answers
Related