• August 23, 2014
  • Core Java
  • Comments Off on Encapsulation in java

Encapsulation in java

Dictionary meaning of Encapsulation:

The condition of being enclosed.

Capsule:

Capsule refers to a small container which contains a dose of medicine.

Definition of Encapsulation:

Encapsulation is a process of wrapping code and data into a single unit.

Encapsulation in real world:

Let us take an example of a HR in a company. We communicate through HR not directly with the departments. HR is acting as a public interface here.

Encapsulation in programming:

Encapsulation is the way of declaring the data members as private and providing access to the data members through public methods (getter and setter methods). As private field can’t be access outside the class that means data is hiding within the class. That’s why encapsulation is also known as data hiding.

Important points:

1. Main Concept behind encapsulation is ‘control over the data’. It is achieved using class and access modifier private, protected, public. Class is act as a container which contains code and data.
2. Factory pattern and Singleton pattern in Java are based on the concept encapsulation.

Example:

Car.java

/**
 * This class is used to set and get car properties.
 * @author javawithease
 */
public class Car {
      //data members
      private int speed;
      private String color;     
 
      //getter setters of above data members.
      public int getSpeed() {
            return speed;
      }
 
      public void setSpeed(int speed) {
            this.speed = speed;
      }
 
      public String getColor() {
            return color;
      }
 
      public void setColor(String color) {
            this.color = color;
      }    
}

CarTest.java

/**
 * This class is used to interact with Car class.
 * @author javawithease
 */
public class CarTest {
      public static void main(String args[]){
            //create Car class object
            Car car1 = new Car();          
 
            //set car details.
            car1.setColor("white");
            car1.setSpeed(120);           
 
            //get and print car details.
            System.out.println("Car color: " + car1.getColor());
            System.out.println("Car speed: " + car1.getSpeed());
      }
}

Output:

Car color: white
Car speed: 120

Download this example.

Advantages/Benefits of Encapsulation:

  1. 1. A read-only (immutable) or write-only class can be made.
  2. 2. Control over the data.
  3. 3. It helps in achieving high cohesion and low coupling in the code.

 
Next Topic: Polymorphism in java.
Previous Topic: Abstraction in java.

Related Topics:

OOPs Basics.
Object and Class in Java.
OOPs Principles/Concepts.
Abstraction in java.
Encapsulation in java.
Polymorphism in java.

 


Comments are closed.