Encapsulation

A real-world example of encapsulation is:

Capsule = combination of two or more medicine.

Car = car body and engine

Encapsulation:

Encapsulation is a mechanism in java by which we wrapping data and code in a single united.

Here data refers to variables

Here Code refers to methods acting on variable

How To achieve encapsulation:

  1. We have to declare a variable of class as private
  2. Provide public getter and setters method to modify and view the variable value

Data Hiding:

The variable of the class is hidden for other class and only accessible by the method of the same class

This concept is known as Data Hiding.

Example:

public class Student {
    private int name; // this is data hiding
}

See examples of encapsulation:

public class Student{
    
    private String studentname; // this is data hiding
    
    public void setStudentName(String student1)
    {
        studentname  = student1;
    }
    
    public String getStudentName()
    {
        return studentname;
    }
    
     public static void main (String[]args){
         Student st = new Student();
         st.setStudentName("Rahul");
         System.out.println(st.getStudentName());
     }
}
Rahul

Here our data is safe and we can control our data in encapsulation.



SHARE THIS PAGE





Important Link