Encapsulation in java

Encapsulation
in java is a process of wrapping code and data together into a single unit or Encapsulation
is the packing of data and functions into a single component.

Encapsulation
is also known as “data hiding”. For
example a CPU of computer is mixed
of several parts.

If a data
member is private it means it can only be accessed within the same class. No
outside class can access private data member (variable) of other class.

The Java Bean class is the example of fully
encapsulated class.

Advantages of Encapsulation -:

1.It improve maintainability,
flexibility and re –usability. In encapsulation we have need two method getter
and setter. For example in a class we have two methods getData () and setData (String
data).

Example of class

Class demo

{

private
String mdata;

public
String getData()

{

return
mdata;

}

Public void
setData(String data)

{

Mdata=data;

}

}

In the above
code the implementation code of void setData (String data) and String getData
() can be changed at any point of time. Hence the code can be maintained at any
point of time without breaking the classes that uses the code. This improves
the re-usability of the underlying class.

2.Fields can be made read only or write
only. For example we have fields which can’t change then we can set in private
variable and remove setter method for set data can only make getter.

3.It hides implementation for example
you are calling setData(String data) and you don’t know what is happening
behind the setData methods.