Encapsulation

Encapsulation
  • Encapsulation is one of the oops concept
  • Binding (or wrapping) code and data together into a single unit is known as encapsulation.
  • A java class is the example of encapsulation.
  • In java method perfect example of encapsulation.
  • Java bean is the fully encapsulated class because all the data members are private here.
  • Encapsulation used to provide security.
Java Bean class Example
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
class Employee
{
 
	private int id;
	private String name;
	private double salary;
 
 
	public Employee(int id,String name,double salary)
	{
 
		this.id=id;
		this.name=name;
		this.salary=salary;
 
	}
 
 
	//public getter and setter method
 
	public int getid()
	{
		return id;
	}
 
	public void setid(int id)
	{
		this.id=id;
	}
 
 
	public String getname()
	{
		return "bhavesh";
	}
 
 
	public void setname(String name)
	{
		this.name=name;
	}
 
 
	public double getsalary()
	{
		return salary ;
	}
 
	public void setsalary(double salary)
	{
		this.salary=salary;
	}
 
}
 
 
public class JavaBeanclass
{
 
	public static void main(String[] args) {
 
		System.out.println("***************************");
 
 
		Employee emp=new Employee(1, "bhavesh", 23.9);
 
		System.out.println("Employee id: "+emp.getid());
		System.out.println("Employee name: "+emp.getname());
		System.out.println("Employee salary: "+emp.getsalary());
 
 
		System.out.println("***************************");
 
		emp.setsalary(2344.23);
 
		System.out.println("Employee Salry: "+emp.getsalary());
	}
 
}
 
output:
 
***************************
Employee id: 1
Employee name: bhavesh
Employee salary: 23.9
***************************
Employee Salry: 2344.23