惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Announcements
Recent Announcements
博客园 - Franky
博客园 - 三生石上(FineUI控件)
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Apple Machine Learning Research
Apple Machine Learning Research
云风的 BLOG
云风的 BLOG
人人都是产品经理
人人都是产品经理
博客园 - 【当耐特】
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
H
Help Net Security
爱范儿
爱范儿
罗磊的独立博客
博客园_首页
美团技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
量子位
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 叶小钗
V
Visual Studio Blog
T
Tailwind CSS Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Abstraction vs. Encapsulation — What’s the Difference? (S...
SAURAV KUMAR · 2026-04-22 · via DEV Community

If you are learning Object-Oriented Programming (OOP), you have definitely seen these two words: Abstraction and Encapsulation.

They sound similar. They both involve "hiding" things. And that is why almost every beginner gets confused between them.

When I started learning OOP, I used to think they were the same thing. But they are not. They have different goals and solve different problems.

In this post, let’s break down the difference in very simple words.


🔍 The Main Difference in One Sentence

If you only remember one thing from this post, let it be this:

Abstraction hides complexity (the "how"), while Encapsulation hides data (the "state").


🧱 1. Abstraction (Hiding Complexity)

Abstraction is about simplicity.

It is the process of hiding the internal working of a system and showing only the essential parts to the user.

Real-Life Example: The TV Remote

When you use a TV remote, you only care about the buttons: Power, Volume, and Channel. You don't care about the infrared signals or the circuit board inside.

The remote abstracts the complex electronics away and gives you a simple interface.

Goal: To make the system easier to use.


📦 2. Encapsulation (Hiding Data)

Encapsulation is about safety and control.

It is the process of wrapping data (variables) and behavior (methods) into a single unit (a class) and restricting direct access to that data.

Real-Life Example: A Medical Capsule

Think of a medicine capsule. The medicine is inside the shell. You can't touch the powder directly; you have to take the whole capsule.

In code, we "shell" our data so it can't be changed by mistake from the outside.

Goal: To protect the data from being corrupted or accessed incorrectly.


💻 Let's See Both in JavaScript

Here is a BankAccount class that uses both concepts:

class BankAccount {
  #balance = 0; // Encapsulation: The balance is hidden and protected

  // Abstraction: The user only sees "deposit"
  // They don't see the internal verification logic
  deposit(amount) {
    if (amount > 0) {
      this.#verifyTransaction(); // Hidden internal step
      this.#balance += amount;
      console.log(`Deposited: $${amount}`);
    }
  }

  // This is hidden logic (Abstraction)
  #verifyTransaction() {
    console.log("Verifying transaction with bank servers...");
  }

  checkBalance() {
    console.log(`Current Balance: $${this.#balance}`);
  }
}

const myAccount = new BankAccount();
myAccount.deposit(500); // Simple interface
myAccount.checkBalance(); 

// This will throw an error because of Encapsulation
// myAccount.#balance = 1000000; 

Enter fullscreen mode Exit fullscreen mode

In this example:

  1. Abstraction: You only use deposit() and checkBalance(). You don't need to know about #verifyTransaction().
  2. Encapsulation: You cannot change #balance directly. You must go through the deposit() method.

⚖️ Side-by-Side Comparison

Feature Abstraction Encapsulation
Focus Hides implementation (Complexity) Hides data (State)
Goal Make it easier to use Make it safer to use
Question "What does it do?" "How do I protect it?"
Example Using a steering wheel Hiding the engine parts

🚀 Revision Cheat Sheet

If you come back to this post later to revise, just read this:

  • Need simplicity? Use Abstraction (Hide the messy details).
  • Need safety? Use Encapsulation (Hide the sensitive data).
  • Tool for Abstraction: Simple public methods.
  • Tool for Encapsulation: Private properties (#) and getter/setter methods.

Example Summary:
The steering wheel is an abstraction. The locked hood of the car is encapsulation.


❌ Common Beginner Confusion

"Wait, isn't hiding a private method part of Encapsulation?"

This is the tricky part. Technically, using private methods (#methodName) is a tool of Encapsulation, but when you use it to simplify the class for the user, you are achieving Abstraction.

They often work together!


🎯 Interview-Friendly Answer

If an interviewer asks for the difference, you can say:

"Abstraction is the process of hiding implementation details to reduce complexity and make the system easier to use. Encapsulation is the process of bundling data and methods together and restricting direct access to the data to ensure safety and control."


✅ Final Thoughts

Think of Abstraction as the "User Manual" (simple instructions) and Encapsulation as the "Security Guard" (protecting the internals).

If you are building an app, use Abstraction to keep your code clean and Encapsulation to keep your data safe.


🙋‍♂️ About Me

Hi, I’m Saurav Kumar.

I enjoy learning, building, and writing about web development in simple words—especially breaking down topics that are useful for beginners and developers preparing for interviews.

Right now, I’m focusing on deepening my understanding of core concepts like JavaScript, OOP, system design, and software engineering fundamentals.

Let's connect!