Difference Between Encapsulation and Abstraction Explained

Are you struggling to develop clean, efficient and maintainable code? The two key principles of Object-Oriented Programming (OOP), encapsulation and abstraction, can come to your aid. While one helps maintain privacy, the other offers simplification of complex systems. To help you with the Encapsulation vs Abstraction comparison, here’s a detailed guide.

Difference Between Encapsulation and Abstraction

The difference between data abstraction and encapsulation as per different parameters is as follows:

Parameter 

Encapsulation 

Abstraction 

Objective 

Wraps data and method to form a single unit 

Hide complex and unnecessary details except for the important part 

Usage 

To maintain privacy to avoid unauthorized access

Decrease complexity by hiding the essential features 

Implementation 

Performed through access modifiers such as public, private and protected 

Done via abstract classes and interfaces 

Function 

Contains the information 

Gains the information 

Dependency 

Data is not necessary to be abstracted for encapsulation 

Data is encapsulated for abstraction 

Focus 

Involves ‘how’ object performs the action 

Involves ‘what’ action object performs

Offers solution at 

Deals with issues at the implementation level 

Deals with issues at the design level 

What is Encapsulation?

The concept of encapsulation offers a method to prevent unauthorized access to the data and methods. The process is a feature of Object-Oriented Programming (OOP) that takes place by binding or grouping the data and method/variables to form a single unit, decreasing the visible part of the code. 

It is performed through private variable declaration along with the inclusion of public methods for obtaining the values of variables. Encapsulation leads to limited access to data, which is possible via the member function of the class where they are declared. Hence, only authorized users can modify the data. 

"Encapsulation is the bundling of data with the methods that operate on that data."
- Herbert Schildt

Example of Encapsulation

Let’s say there is a class ‘Vehicle’ that encapsulates the internal and private details of how the vehicle works, which includes fuel level and engine state. The ‘Car’ and ‘Motorcycle’ are public methods that hold access to these details in a controlled manner. Here is the program in Java depicting the scenario:

// Base class Vehicle (encapsulating internal details)

class Vehicle {

    // Private variables (encapsulation)

    private int fuelLevel;        // Fuel level in percentage (0 to 100)

    private boolean engineState;  // Engine state (true = running, false = stopped)


    // Constructor to initialize fuel level and engine state

    public Vehicle(int fuelLevel) {

        this.fuelLevel = fuelLevel;

        this.engineState = false;  // Engine is off by default

    }


    // Public method to get fuel level

    public int getFuelLevel() {

        return fuelLevel;

    }


    // Public method to set fuel level

    public void setFuelLevel(int fuelAmount) {

        if (fuelAmount >= 0 && fuelAmount <= 100) {

            this.fuelLevel = fuelAmount;

        } else {

            System.out.println("Invalid fuel level. Must be between 0 and 100.");

        }

    }


    // Public method to start the engine

    public void startEngine() {

        if (fuelLevel > 0) {

            engineState = true;

            System.out.println("Engine started.");

        } else {

            System.out.println("Cannot start engine. No fuel.");

        }

    }


    // Public method to stop the engine

    public void stopEngine() {

        engineState = false;

        System.out.println("Engine stopped.");

    }


    // Public method to check if engine is running

    public boolean isEngineRunning() {

        return engineState;

    }

}


// Derived class Car

class Car extends Vehicle {

    // Constructor for Car

    public Car(int fuelLevel) {

        super(fuelLevel);  // Initialize fuel level using Vehicle constructor

    }


    // Method for driving the car

    public void drive() {

        if (isEngineRunning()) {

            System.out.println("The car is driving.");

        } else {

            System.out.println("Start the engine first.");

        }

    }

}


// Derived class Motorcycle

class Motorcycle extends Vehicle {

    // Constructor for Motorcycle

    public Motorcycle(int fuelLevel) {

        super(fuelLevel);  // Initialize fuel level using Vehicle constructor

    }


    // Method for driving the motorcycle

    public void drive() {

        if (isEngineRunning()) {

            System.out.println("The motorcycle is driving.");

        } else {

            System.out.println("Start the engine first.");

        }

    }

}


// Main class to test the example

public class Main {

    public static void main(String[] args) {

        // Create a car and motorcycle with initial fuel levels

        Car myCar = new Car(50);

        Motorcycle myBike = new Motorcycle(10);


        // Try to drive the car and bike without starting the engine

        myCar.drive();  // Engine should be started first

        myBike.drive(); // Engine should be started first


        // Start the car engine and drive

        myCar.startEngine();

        myCar.drive();  // Now the car can drive


        // Set new fuel level for the bike and start the engine

        myBike.setFuelLevel(20);

        myBike.startEngine();

        myBike.drive();  // Now the motorcycle can drive


        // Stop the car engine

        myCar.stopEngine();

    }

}

The output of the program will be: 

Start the engine first.

Start the engine first.

Engine started.

The car is driving.

Invalid fuel level. Must be between 0 and 100.

Engine started.

The motorcycle is driving.

Engine stopped.

Application of Encapsulation

Common usage of the software on your mobile phone or laptop to perform a plethora of tasks is an example of encapsulation. Here, the users simply need to interact by clicking or touching the icons to click or view pictures, browse the web, and do other things. Performing these tasks does not require understanding the mechanism or flow of action. 

Apart from this, entering a password to log into the app involves the usage of encapsulation. It keeps the password safe by not allowing unauthorized access to the account. Only the entry of specific login credentials offers access to the account. 

Unleash Your Career as a Full Stack Developer!

Full Stack Developer - MERN StackEXPLORE COURSE
Unleash Your Career as a Full Stack Developer!

What is Abstraction?

This concept in Object-Oriented Programming aims to exhibit the essential details or methods to the user. Hence, unnecessary data is hidden here through the interface and abstract class. The process can also be considered as a method of recognition of key characteristics of an object. It reduces complexity while enhancing efficiency. 

"Abstraction is the art of ignoring detail."
- Edsger W. Dijkstra

Example of Abstraction

Let’s continue with the previous example. It has an abstract class, ‘Vehicle’, that represents common actions that it is able to perform. The ‘Car’ and ‘Motorcycle’ are two classes that inherit from the mentioned class and define specific behaviors for each type of vehicle. Here, an interface like ‘VehicleService’ can define actions like different vehicle servicing possibilities. The depiction in program form in Java is as follows: 

// Abstract class representing a generic Vehicle

abstract class Vehicle {

    // Encapsulated field representing the fuel level of the vehicle

    private int fuelLevel;


    // Constructor to initialize fuel level

    public Vehicle(int fuelLevel) {

        this.fuelLevel = fuelLevel;

    }


    // Getter and setter for fuel level (Encapsulation)

    public int getFuelLevel() {

        return fuelLevel;

    }


    public void setFuelLevel(int fuelLevel) {

        if (fuelLevel >= 0 && fuelLevel <= 100) {

            this.fuelLevel = fuelLevel;

        } else {

            System.out.println("Invalid fuel level. Must be between 0 and 100.");

        }

    }


    // Abstract method that forces subclasses to implement the drive behavior (Abstraction)

    public abstract void drive();

}


// Interface defining the service actions for vehicles

interface VehicleService {

    void serviceVehicle();  // Method to service the vehicle

}


// Concrete class Car that extends Vehicle and implements VehicleService

class Car extends Vehicle implements VehicleService {


    // Constructor for Car class

    public Car(int fuelLevel) {

        super(fuelLevel);  // Call the parent constructor to initialize fuel level

    }


    // Implementation of the drive method specific to Car

    @Override

    public void drive() {

        if (getFuelLevel() > 0) {

            System.out.println("Car is driving.");

        } else {

            System.out.println("No fuel! Can't drive the car.");

        }

    }


    // Implementation of the serviceVehicle method specific to Car

    @Override

    public void serviceVehicle() {

        System.out.println("Performing routine service on the car.");

    }

}


// Concrete class Motorcycle that extends Vehicle and implements VehicleService

class Motorcycle extends Vehicle implements VehicleService {


    // Constructor for Motorcycle class

    public Motorcycle(int fuelLevel) {

        super(fuelLevel);  // Call the parent constructor to initialize fuel level

    }


    // Implementation of the drive method specific to Motorcycle

    @Override

    public void drive() {

        if (getFuelLevel() > 0) {

            System.out.println("Motorcycle is driving.");

        } else {

            System.out.println("No fuel! Can't drive the motorcycle.");

        }

    }


    // Implementation of the serviceVehicle method specific to Motorcycle

    @Override

    public void serviceVehicle() {

        System.out.println("Performing routine service on the motorcycle.");

    }

}


// Main class to test the abstraction and interface implementation

public class Main {

    public static void main(String[] args) {

        // Create instances of Car and Motorcycle

        Car myCar = new Car(50);  // Car with 50% fuel

        Motorcycle myMotorcycle = new Motorcycle(20);  // Motorcycle with 20% fuel


        // Test driving functionality

        myCar.drive();  // Should print: "Car is driving."

        myMotorcycle.drive();  // Should print: "Motorcycle is driving."


        // Service the vehicles

        myCar.serviceVehicle();  // Should print: "Performing routine service on the car."

        myMotorcycle.serviceVehicle();  // Should print: "Performing routine service on the motorcycle."


        // Test cases where vehicles have no fuel

        myCar.setFuelLevel(0);

        myCar.drive();  // Should print: "No fuel! Can't drive the car."

        myMotorcycle.setFuelLevel(0);

        myMotorcycle.drive();  // Should print: "No fuel! Can't drive the motorcycle."

    }

}

The output of the program will be: 

Car is driving.

Motorcycle is driving.

Performing routine service on the car.

Performing routine service on the motorcycle.

No fuel! Can't drive the car.

No fuel! Can't drive the motorcycle.

Application of Abstraction

Mobile phones and laptops also exhibit the application of abstraction. It is as the users don’t need to access or understand the method of handling network connections, managing system resources, or optimizing battery life. Similarly, another common application of abstraction is evident in ATMs. Here, numerous functions are performed through the device without the requirement to enter the processing method. 

Encapsulation vs Abstraction in Java

The encapsulation vs abstraction in Java can be distinguished as follows: 

Meaning: Encapsulations refer to controlling access to the data while hiding it. Abstraction also involves data hiding but along with code implementation

Phase: Encapsulation requires implementation, while abstraction is a design-level process that is possible without implementation. 

Function: Encapsulation is used to control data transparency. It helps in code organization. Abstraction deals with the possible function of a class instance. It reduces complexity by presenting only the essential data. 

Implementation: Encapsulation is implemented via the usage of classes where data privacy is achieved through the specification of access specifiers such as private, public and protected. Abstraction is implemented through classes and interfaces in Java. 

Program partition: Encapsulation adapts to different requirements via controlling access through the getters and setters method. The abstraction partitions the program into different fragments. 

Benefit: Encapsulation eases code modification. The abstraction offers the benefit of code reusage and extendability. 

Conclusion

Being important in Object-Oriented Programming (OOP), encapsulation and abstraction serve significant purposes during coding. When dealing with the writing usage of data, programmers will need to dive into these two concepts in-depth, along with multiple others. If your situation or goals align with the mentioned tasks and you lack basic understanding or hands-on experience, it's time to skill up. 

Simplilearn brings you the Full Stack (MERN Stack) Developer Masters Program. In collaboration with IBM, it is aimed at developing essential skills to make the candidates job-ready. With over 40 micro-skilling exercises and more than six work-like professional projects, there is so much to grab with the opportunity. Seize the chance by clicking on the link. 

FAQs

1. What is an example of encapsulation and abstraction in real-time?

The vehicle’s steering, brakes and pedals can be considered an example of abstraction, while its engine depicts encapsulation. The unnecessary aspects are hidden in simple functionalities while the engine represents data hiding and prevents unauthorized access. 

2. Is abstraction possible without encapsulation?

While encapsulation is common before abstraction, the task can be achieved without the former as well. 

3. Is abstraction and encapsulation the same in Python?

No, the concepts and their purpose are different and remain consistent across different languages. Hence, they are not the same in Python. 

4. What is an abstraction in OOP?

Abstraction is the concept that aims at reducing complexity by hiding unnecessary details. It increases efficiency and is performed using an abstract class. 

5. What is the difference between data hiding and encapsulation?

Data hiding restricts data usage for security, while encapsulation wraps the data for simplification. Encapsulation is a broad concept comprising different aspects, one of which is data hiding.

About the Author

Kusum SainiKusum Saini

Kusum Saini is the Director - Principal Architect at Simplilearn. She has over 12 years of IT experience, including 3.5 years in the US. She specializes in growth hacking and technical design and excels in n-layer web application development using PHP, Node.js, AngularJS, and AWS technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.