Java Encapsulation


Encapsulation

Encapsulation definition, to ensure that "sensitive" data is hidden from users. To do this, you must:

  • declare class variables/attributes as private
  • provide public get and set methods to access and update the value of a private variable

Get and Set

You learned in the preceding chapter that the private variance can only be achieved in the same class (the external class cannot access it). However, we can only access them if we provide community get and set methods.

The get method returns the variable value, and the set method sets the value.

The syntax for both of you is the one that starts with get or set, followed by the word variable, with the first capital letter:


Example
public class Person {
            private String name; // private = restricted access
          
            // Getter
            public String getName() {
              return name;
            }
          
            // Setter
            public void setName(String newName) {
              this.name = newName;
            }
          }
          

Example explained

The get method returns the value of the variable name.

The set method takes a parameter (newName) and provides a variable name. this keyword is used to refer to the current object.

However, since the name is declared private, we cannot access it without this category:


Example
public class Main {
            public static void main(String[] args) {
              Person myObj = new Person();
              myObj.name = "John";  // error
              System.out.println(myObj.name); // error 
            }
          }
          

Once the variable is declared public, we can expect the following output:

John

However, as we try to access a different public, we find an error:

MyClass.java:4: error: name has private access in Person
    myObj.name = "John";
         ^
MyClass.java:5: error: name has private access in Person
    System.out.println(myObj.name);
                  ^
2 errors

Instead, we use the getName() and setName() methods to access and update variables:


Example
public class Main {
            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());
            }
          }
          
          // Outputs "John"
          


Why Encapsulation?

  • Better control of class attributes and methods
  • Class attributes can only be read-only (if you only use the get method), or write-only (if you only use default method)
  • Correct: The designer can change one part of the code without touching the other parts
  • Additional data protection