HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Java Encapsulation

What is Encapsulation in Java?

Get and Set

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

Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case:

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;
  }
}
             

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

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"
             

Need for Encapsulation in Java: