Bytes
Web Development

Difference Between Abstraction and Encapsulation in Java, C++ and Python

Last Updated: 16th March, 2025
icon

Jay Abhani

Senior Web Development Instructor at almaBetter

Know the difference between abstraction and encapsulation in OOP in Java, C++, Python and C# with examples. Learn how they improve code security and modularity.

In object-oriented programming (OOP), abstraction and encapsulation are two fundamental principles that promote code maintainability, security, and efficiency. While both are related to data hiding, they serve different purposes. Many developers, especially beginners, often confuse them.

This article provides an in-depth comparison of abstraction vs encapsulation, including practical examples in Java, C++, C#, and Python. By the end, you’ll have a clear understanding of their differences and real-world applications.

Understanding Abstraction

What is Abstraction?

Abstraction is the process of hiding implementation details while exposing only the necessary features to the user. It allows programmers to design systems that focus on what an object does rather than how it does it.

Key Features of Abstraction

  • Hides complex implementation details.
  • Exposes only relevant functionalities.
  • Helps in reducing complexity and increasing reusability.
  • Achieved using abstract classes and interfaces.

Example of Abstraction in Real Life

A car’s dashboard is a perfect example of abstraction. When you drive a car, you use a steering wheel, accelerator, and brakes to control it. You don't need to understand how the engine works internally only the necessary functions are available to you.

Understanding Encapsulation

What is Encapsulation?

Encapsulation is the technique of wrapping data (variables) and methods (functions) into a single unit while restricting direct access to the data. It protects an object's integrity by preventing unintended modifications.

Key Features of Encapsulation

  • Protects data by restricting access (using private or protected access modifiers).
  • Data is accessed only via getter and setter methods.
  • Helps achieve data security and modularity.
  • Improves maintainability and flexibility.

Example of Encapsulation in Real Life

Think of a medical pill. The pill contains various ingredients (data), but you cannot directly access them. Instead, you consume the pill as a whole (methods) without knowing its internal composition.

Abstraction vs Encapsulation: Key Differences

Let’s break down the difference between encapsulation and abstraction with a structured comparison.

FeatureAbstractionEncapsulation
DefinitionHides the implementation details and shows only essential features.Hides the data by restricting direct access using access modifiers.
PurposeReduce complexity and increase code reusability.Ensure data security and prevent accidental modifications.
ImplementationAchieved using abstract classes and interfaces.Achieved using access modifiers (private, protected, public) and getter/setter methods.
Data HidingFocuses on hiding implementation details.Focuses on hiding data to protect object integrity.
Main BenefitAllows focus on what an object should do rather than how it does it.Prevents unintended modifications to data and ensures controlled access.
Real-World ExampleA car’s dashboard (You interact with the steering and pedals but don’t need to know how the engine works).A medical pill (The internal ingredients are encapsulated, and you can only use it as intended).
Where Used?Used in designing classes with abstract methods.Used in implementing classes to enforce controlled access to data.
LanguagesImplemented using abstract classes and interfaces in Java, C++, C#, Python.Implemented using access modifiers (private, protected, public) in Java, C++, C#, Python.

Difference Between Abstraction and Encapsulation in Java

Example of Abstraction in Java

Abstraction in Java is achieved using abstract classes and interfaces.

Abstract Class Example

abstract class Vehicle {
    abstract void start()// Abstract method (no implementation)
}

class Car extends Vehicle {
    @Override
    void start() {
        System.out.println("Car starts with a key.");
    }
}

public class AbstractionExample {
    public static void main(String[] args) {
        Vehicle myCar = new Car();
        myCar.start(); // Output: Car starts with a key.
    }
}

Here, the Vehicle class provides abstraction by defining the method start() but not its implementation.

Example of Encapsulation in Java

Encapsulation in Java is achieved using private fields and public getter and setter methods.

Encapsulation Example

class BankAccount {
    private double balance; // Data hidden using private access modifier

    public void setBalance(double balance) {
        if (balance >= 0) {
            this.balance = balance;
        }
    }

    public double getBalance() {
        return balance;
    }
}

public class EncapsulationExample {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        account.setBalance(1000);
        System.out.println("Balance: " + account.getBalance()); // Output: Balance: 1000
    }
}

Here, the balance field is private, and access is controlled through getter and setter methods.

Difference Between Encapsulation and Abstraction in C++

Example of Abstraction in C++

#include <iostream>
using namespace std;

class Vehicle {
public:
    virtual void start() = 0// Pure virtual function (abstraction)
};

class Carpublic Vehicle {
public:
    void start() override {
        cout << "Car starts with a button." << endl;
    }
};

int main() {
    Vehicle* v = new Car();
    v->start(); // Output: Car starts with a button.
    delete v;
}

Example of Encapsulation in C++

#include <iostream>
using namespace std;

class BankAccount {
private:
    double balance;

public:
    void setBalance(double bal) {
        if (bal >= 0)
            balance = bal;
    }

    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account;
    account.setBalance(2000);
    cout << "Balance: " << account.getBalance() << endl; // Output: Balance: 2000
}

Difference Between Abstraction and Encapsulation in Python

Example of Abstraction in Python

from abc import ABC, abstractmethod

class Vehicle(ABC):
    @abstractmethod
    def start(self):
        pass

class Car(Vehicle):
    def start(self):
        print("Car starts with a key.")

car = Car()
car.start() # Output: Car starts with a key.

Example of Encapsulation in Python

class BankAccount:
    def __init__(self):
        self.__balance = 0  # Private variable

    def set_balance(self, balance):
        if balance >= 0:
            self.__balance = balance

    def get_balance(self):
        return self.__balance

account = BankAccount()
account.set_balance(500)
print("Balance:", account.get_balance())  # Output: Balance: 500

More Related Lessons for You

Conclusion

Both abstraction and encapsulation are crucial in OOP but serve different purposes. Abstraction simplifies design by hiding unnecessary details, whereas encapsulation secures data and ensures controlled access. Understanding their difference and implementation in Java, C++, C#, and Python will help you write clean, modular, and secure code.

Frequently asked Questions

What is an example of abstraction and encapsulation in real life?

Abstraction: A car’s dashboard (You only interact with necessary controls). Encapsulation: A medical pill (You can use it but cannot access its components directly).

Can we achieve abstraction without encapsulation in Java?

No, abstraction and encapsulation often work together. However, abstraction focuses on hiding complexity, while encapsulation focuses on protecting data.

Can we achieve 100% abstraction in Java?

Yes, 100% abstraction is achieved using interfaces in Java, where all methods are abstract.

Related Articles

Top Tutorials

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2025 AlmaBetter