Encapsulation in Java explained with example.

 Encapsulation is a fundamental concept in the world of object-oriented programming (OOP) and is widely used in Java. It is the process of hiding the internal details of an object from the outside world. This helps to protect the data and behavior of an object from being modified by external sources, and ensures that the object’s internal state is consistent. In this blog post, we will discuss the concept of encapsulation in Java and how it can be implemented in your code.

encapsulation in java

The main idea behind encapsulation is to restrict access to the member variables and methods of a class. In Java, this can be achieved by using the “private” access modifier. When a variable or method is declared as “private“, it can only be accessed within the class where it is declared. This means that other classes or objects cannot access or modify the private members of a class.

For example, consider the following class “Car“:


public class Car {
    private String make;
    private String model;

    public Car(String make, String model) {
        this.make = make;
        this.model = model;
    }

    public String getMake() {
        return make;
    }

    public String getModel() {
        return model;
    }
}

In this example, the member variables “make” and “model” are declared as private, which means that they can only be accessed within the class “Car“. However, we can still provide access to these variables through public methods such as “getMake()” and “getModel()“. This way, the internal state of the class can be accessed and modified in a controlled manner.

Encapsulation also promotes the concept of data hiding, which means that the internal state of an object should not be exposed to the outside world. Instead, the object should provide a set of methods that allow the user to interact with it in a controlled way. This helps to ensure that the object’s internal state remains consistent, and that any changes to the object’s state are made in a controlled and predictable manner.

In conclusion, encapsulation is an important concept in OOP and Java. It allows you to restrict access to the member variables and methods of a class, and helps to protect the data and behavior of an object from being modified by external sources. By using encapsulation, you can ensure that the internal state of your objects remains consistent and that any changes to the object’s state are made in a controlled and predictable manner.