3

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?

user148647
  • 31
  • 3
  • I was about to answer but before I could post it. It was marked as duplicate. I will try to explain it with a simple example: http://ideone.com/7eGPYl Take a look at `setMarks()` method. It is restricting the value of `marks` within 0-100 range. If you make it `public` you can't control the assigned value. – Mushif Ali Nawaz Oct 10 '19 at 07:23
  • The point of hiding variable inside a class is to _control access points_. This point and has nothing to do with OOP and incapsulation. Robert Martin in Clean Code explains it this way: (1) you may need a _data structure_ - it aggregates data fields, exposes them (directly or by get/set methods) and does not contain sensible methods. (2) and you may need an _object_ - a true OOP unit, that does not show it's internal structure (fields), but provides usable methods to _do work_. He concludes: wise programmer choose guided by a task, environment and the general solution architecture. – lotor Oct 10 '19 at 07:26
  • @MushifAliNawaz I thought that the restriction should be given in the private method. Giving it in the public allows someone to modify it. What's your opinion on that? – user148647 Oct 10 '19 at 07:43
  • @user148647 Still the access it through the public setter. Have you checked the code I provided? Please check this link: http://ideone.com/7eGPYl – Mushif Ali Nawaz Oct 10 '19 at 07:46
  • @MushifAliNawaz Yes, about the code you sent was the comment. Why the restriction is not in the private where nobody can access it? Wouldn't that be more efficient in enforcing the rule? – user148647 Oct 10 '19 at 08:38
  • @user148647 if the method is `private` then it won't be called from outside the `class`. But here the `marks` field is `private` so it can't be accessed outside the class. Here we will provide `public` getter and setter that will allow to access/modify the values. In the setter method, we can enforce the validation. – Mushif Ali Nawaz Oct 10 '19 at 08:53

0 Answers0