Encapsulation in Java

Encapsulation is another basic principle of object-oriented programming. It involves hiding data from external access.

Introducing encapsulation in Java is extremely important, especially in large projects.

By following the encapsulation rules, we ensure that objects have strictly controlled inputs and outputs and thus reduce the possibility of error, logical inconsistency, or errors in the program.

We provide data hiding by using the keyword private. That way, no one outside that class can change the data unplanned.

Each access to data is done exclusively through public methods created for these purposes, which are getter and setter methods.

The getter method is used to retrieve data, i.e. it returns the value of a variable, while the setter method is used to set a new value for the variable.

We can make the class read-only or write-only by providing only the setter or getter method. In this way, we provide control over the data.


public class Student {
  private String name;
  public String getName() {
    return name;
  public void setName(String name) {
    this.name = name
class Test {
  public static void main(String[] args) {
    Student s = new Student();
    // System.out.println(s.name); // DOES NOT COMPILE
Output: John
If we try to access a private member of some class from another class, we will get a compiler error. So we use getter and setter methods to access the variable and assign a value to it.

That’s it!

Leave a Reply

Your email address will not be published.