Java Tutorial-Java Encapsulation

Java Encapsulation


The Encapsulation helps to hide the “sensitive” data from users. To achieve this, we need to

  • declare the variables / attributes as private (only accessible within the same class)
  •  provide the public setter and getter method to access and update the value of a private variable

 

Getter and Setter Method


The private variable can only be accessed within the same class. From outside the class, we do not have access for the private attributes. However, we could able to access those variables using public setter and getter methods.

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

The syntax for both the methods start either with get or set, followed by the name of the variable, with the first letter of the variable in Upper case:

 

Example

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

 

Example Explained

  •  The get method getName() will returns the value of the variable name.
  • The set method setName() takes the parameter newName and assign to the variable name. This keyword is used to refer to the current object.
  • However, as we declare the name as private, we cannot access it from outside this class.

Example – Accessing the private variable


Here we see what happens when we try to access the private variable in the above example.

public class GetSetMainMethod {
       public static void main(String args[]){
              GetSetMethod gsObj = new GetSetMethod();
              gsObj.name = "Johnson";
              System.out.println(gsObj.name);
       }
}

 

Error Message

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
       The field GetSetMethod.name is not visible
       The field GetSetMethod.name is not visible
 
       at practices.GetSetMainMethod.main(GetSetMainMethod.java:6)

 Instead we use get and set method to avoid the above error :

public class GetSetMainMethod {
       public static void main(String args[]){
              GetSetMethod gsObj = new GetSetMethod();
              gsObj.setName("Johnson");
              System.out.println(gsObj.getName());
       }
}

 

Output

Johnson

 

Why Encapsulation?


  • Class variables can be made read-only (if we omit the set method) or write-only (if we omit the get method).
  • We can have the better control of class attributes and methods.
  • We can increase the security of data.
  • This makes the code more flexible. The programmer can change one part of the code without affecting the other parts.

·