Java Encapsulation


Java Encapsulation is a mechanism of wrapping up of the data and code together into a single unit.

Encapsulation is also known as Data Hiding because in encapsulation, the variables of one class are hidden from other classes and can be accessed only by methods of their current class.

We can create a fully encapsulated java class by making all the data members of a class as private and to get and set the data in those members we can use getter() and setter() methods.

By providing the setter or getter methods, we can make the fields of the class as read-only or write-only.

With Encapsulation, a class can have total control over what is stored in its fields.


Example:

public class Student
{
    private String name;  
    private int rollNo;

    public void setName(String name)
    {  
        this.name=name;
    }
    
    public void setRollNo(int rollNo)
    {  
        this.rollNo=rollNo;
    }

    public String getName()
    {  
        return name;  
    }

    public int getRollNo()
    {  
        return rollNo;  
    }
}

class EncapsulationExample
{  
    public static void main(String[] args)
    {  
        Student s=new Student();  
        s.setName("Raj");
        s.setRollNo(21);
        System.out.println(“Name : “+s.getName());
        System.out.println(“RollNo : “+s.getRollNo());
    }
}