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)





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.

      Here I am creating an example of encapsulation 



public class Student {    


     public static void main(String args[]) {

           // Constructor of encapsulated class

           MyEncasulatedClass myclass = new MyEncasulatedClass();

           // set data in constructor class


           myclass.setStudentName("Zack Parker");



           // get data in constructor class

   System.out.println("Student Id-:     " + myclass.getStudentId());

  System.out.println("Student Name-:   " + myclass.getStudentName());

  System.out.print("Student Course-:  " + myclass.getStudentCourse());





// Encapsulated class

class MyEncasulatedClass {

     // add private variable

     private int sid;

     private String s_name;

     private String scourse;


     // add getter and setter method

     public void setStudentId(int id) {

           sid = id;



     public int getStudentId() {

           return sid;



     public void setStudentName(String name) {

           s_name = name;



     public String getStudentName() {

           return s_name;



     public void setStudentCourse(String course) {

           scourse = course;



     public String getStudentCourse() {

           return scourse;




Now run your application


Leave Comment