Data Encapsulation In Java
ENCAPSULATION
Encapsulation
is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates.
In Encapsulation
, the variables or data of a class is hidden from any other class and can be accessed only through any member function of its own class in which it is declared.
It is also known as a combination of data-hiding and abstraction.
Implementation of DATA ENCAPSULATION in JAVA
Program to show Data Enacpsulation:
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
class Encapsulate {
// private variables declared
// these can only be accessed by
// public methods of class
private String StudentName;
private int StudentRoll;
private int StudentAge;
// get method for age to access
// private variable StudentAge
public int getAge() { return StudentAge; }
// get method for name to access
// private variable STudentName
public String getName() { return StudentName; }
// get method for roll to access
// private variable StudentRoll
public int getRoll() { return StudentRoll; }
// set method for age to access
// private variable Studentage
public void setAge(int newAge) { StudentAge = newAge; }
// set method for name to access
// private variable StudentName
public void setName(String newName)
{
StudentName = newName;
}
// set method for roll to access
// private variable StudentRoll
public void setRoll(int newRoll) { StudentRoll = newRoll; }
}
public class TestEncapsulation {
public static void main(String[] args)
{
Encapsulate obj = new Encapsulate();
// setting values
obj.setName("Vasav");
obj.setAge(19);
obj.setRoll(51);
System.out.println("Student name: " + obj.getName());
System.out.println("Student age: " + obj.getAge());
System.out.println("Student roll: " + obj.getRoll());
// Direct access of StudentRoll is not possible
// due to encapsulation
}
}
Output
1
2
3
4
5
6
7
Student name: Vasav
Student age: 19
Student roll: 51
In the above program, the class Encapsulate is encapsulated as the variables are declared as private. The get
methods like getAge() , getName() , getRoll() are set as public, these methods are used to access these variables. The setter
methods like setName(), setAge(), setRoll() are also declared as public and are used to set the values of the variables.
Uses And Advantages Of Data Abstraction
-
Data Hiding
: The user will have no information about the private data variables. -
Increased Flexibility
-
Use in Big e-Commerce websites.
-
It reduces Human error.