Continuing from Previous discussion : OOPS : Concept

Encapsulation is one of the fundamental OOP concepts.

Encapsulation is mechanism of wrapping of data ( variable ) and operations ( methods ) into a single unit ( called class ).

In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of the class. Therefore, it is also termed as concept of data hiding.

How do we can hide the variable ?

Using access specifiers
access specifiers are used to control visibility of data
 Java provides private, protected, public and package (default scope) as access specifiers.

How to achieve Encapsulation in Java?

Steps to design the class with Encapsulation concepts:
Declare the variables of a class as private.
Provide public setter and getter methods to modify and access the data variables.
setter is used to set the data(variable).
getter is used to access the data(variable).


class KeyPad {

         private  int number; // accessible only inside the class

           public void setNumber ( int number ) { // accessible through object anywhere
                         this.number = number;

           public int getNumber ( ) { // accessible through object anywhere
                         return number;