Encapsulation in Java | What is Encapsulation in Java?

 


What is Encapsulation in Java? How to Achieve it?


Encapsulation is one of the four fundamental principles of object-oriented programming (OOP) that is used to hide the internal details of an object and restrict access to its properties and methods. It is also referred to as data hiding.



Encapsulation is achieved by using access modifiers such as private, protected, and public to control access to the properties and methods of an object. 

The private access modifier is used to restrict access to the properties and methods of an object to the class itself, making them invisible to the outside world. 

The protected access modifier is used to restrict access to the properties and methods of an object to the class and its subclasses. 

The public access modifier is used to make the properties and methods of an object visible and accessible to the outside world.



For example, consider a class called "Car" that has properties such as "speed" and "fuel level" that are private. 

The class also has methods such as "accelerate()" and "brake()" that are public. 

The private properties can only be accessed and modified by the methods within the class, while the public methods can be called by any object that has a reference to the "Car" object.



class Car {
 
    private int speed;
 
    private int fuelLevel;
 
  public void accelerate(int speed) {
 
        this.speed += speed;
 
    }
 
    public void brake() {
 
        this.speed = 0;
 
    }
 
}



In this example, the speed and fuel level properties are private so they can only be accessed and modified by the methods within the class. The accelerate() and brake() methods are public, so they can be called by any object that has a reference to the "Car" object. This ensures that the internal state of the "Car" object is protected and can only be changed in a controlled manner.



Encapsulation also allows you to change the implementation of the class without affecting the other classes that are using it, this is called Information hiding, this way it becomes more maintainable and flexible.

Post a Comment

Post a Comment (0)

Previous Post Next Post