Objects

Encapsulation

🙋 Need help? Ask an expert now!

Encapsulation is the idea of withholding the details of an object from other parts of the program while allowing its use. The object is only used through its access methods, which are carefully written to keep the object consistent and secure. We use the Java reserved word private to guarantee other classes have no access to the member of a certain class. Let's see how a private variable has access methods that allow it to be viewed.

EncapsulationExample.java
package exlcode;

public class EncapsulationExample {

  public static void main(String[] args) {
    EncapsulationTest encapsulationTest = new EncapsulationTest();
    System.out.println(encapsulationTest.getVariableOne());
  }
}
EncapsulationTest.java
package exlcode;

public class EncapsulationTest {

  private String exampleVariableOne = "Hello World!";

  // private variables can be accessible through
  // public methods
  public String getVariableOne() {
    return exampleVariableOne;
  }
}

The EncapsulationTest class consists of two main members, the private variable exampleVariableOne and the method getVariableOne(). This is a "getter" method, which returns the value of a private member of the class. This method ensures exampleVariableOne will never be in danger of being changed or manipulated even though it is visible through the getter method. This is one example of how encapsulation works. It's a concept that will help you avoid unwanted errors when writing big programs.

Application Question

Which of the following best describe encapsulation?