1// java program on encapsulation
2class EncapsulationExample
3{
4 private int ID;
5 private String stuName;
6 private int stuAge;
7 // getter and setter methods
8 public int getStudentID()
9 {
10 return ID;
11 }
12 public String getStudentName()
13 {
14 return stuName;
15 }
16 public int getStudentAge()
17 {
18 return stuAge;
19 }
20 public void setStudentAge(int number)
21 {
22 stuAge = number;
23 }
24 public void setStudentName(String number)
25 {
26 stuName = number;
27 }
28 public void setStudentID(int number)
29 {
30 ID = number;
31 }
32}
33public class ExampleForEncapsulation
34{
35 public static void main(String[] args)
36 {
37 EncapsulationExample student = new EncapsulationExample();
38 student.setStudentName("Virat");
39 student.setStudentAge(5);
40 student.setStudentID(2353);
41 System.out.println("Student Name: " + student.getStudentName());
42 System.out.println("Student ID: " + student.getStudentID());
43 System.out.println("Student Age: " + student.getStudentAge());
44 }
45}
1Encapsulation focus on Private Data
2Encapsulation allows the programmer to hide
3and restrict access to data.
4To achieve encapsulation:
51.Declare the variables with the private access modifier
62.Create public getters and setters that allow indirect
7access to those variables
8
9Framework Example:
10In my project I created multiple POJO/BEAN classes in order
11to manage test data and actual data.
12I take JSON from API response and convert
13to object of my POJO class.
14All the variables are private with getters and setter.
15Also in order to store credentials or sensitive data
16in my framework I have use encapsulation, configuration reader
17also known as property file or excel sheet to hide data
18from the outside. I use Apache POI if the data is stored in Excel
19in order to extract/read and modify data.
20Partial Encapsulation Usage / getters and setters have to be Public
21We can provide only getters in a class to make the class immutable.
22(Read only) returning private instance variable that’s all
23We provide setters in a class to make the class attribute write-only,
24and return type is void just initialize the given argument
11-ENCAPSULATION: We can hide direct access to data by using
2private key and we can access private data by using getter and
3setter method.