Encapsulation is one of the four fundamental OOP concepts. Encapsulation in Java is defined as the wrapping up of data(variable) under a single unit. The use of Encapsulation is to make sure that implementation detail or we can say sensitive data is hidden from the users. For this, Encapsulation is also known as data hiding.
Implementing the encapsulation in the program, the variables or data declared in one of the classes is hidden from any other class.
Encapsulation can be achieved in two ways:
- Declare class variables/attributes as private, restricting other classes to access it.
- Provide public setter and getter methods to modify and view the values of the variables.
Benefits of Encapsulation:
- Data- hiding in Java.
- The class field can be made read-only or write-only.
- It provides the class the total control over the data.
Get and Set:
As we know the private variable cannot be accessed by other classes, but we can access them by providing getter and setter methods.
- The get method returns the variable value.
- The set method sets the value.
Note:
Getter and Setter methods should start with get or set, followed by the variable name whose first letter should be in upper case. They both should be declared public. Since get returns value and set doesn’t get should be of data-type same as the variable it accesses and set must be declared void.
Syntax Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class Student { private String name; // private // Getter public String getName() { return name; } // Setter public void setName(String newName) { this.name = newName; } } |
Let us go through a java example to understand better
Encapsulation in Java using setter and getter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | class StudentInfo { private int id; private String stdName; private int stdAge; //Getter methods public int geStdiID() { return id; } public String getStdName() { return stdName; } public int getStdAge() { return stdAge; } // Setter methods public void geStdiID(int newId) { id = newId; } public void getStdName(String newName) { stdName = newName; } public void getStdAge(int newAge) { stdAge = newAge; } } public class EncapsTest { public static void main(String args[]) { StudentInfo obj = new StudentInfo(); obj.geStdiID(1101); obj.getStdName("Marshall"); obj.getStdAge(20); System.out.println("Student Id: " + obj.geStdiID()); System.out.println("Student Name: " + obj.getStdName()); System.out.println("Student Age: " + obj.getStdAge()); } } |
Output:
Student Id: 1101
Student Name: Marshall
Student Age: 20