Java Encapsulation
The Encapsulation helps to hide the “sensitive” data from users. To achieve this, we need to
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
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)
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?
·