Abstraction ✔
- Encapsulation → protecting correctness
- Abstraction → defining capability and role
Abstraction is the principle of:
Focusing on what an object does, not how it does it.
It defines:
- Interfaces
- Contracts
- Boundaries between components
While encapsulation hides internal state,
abstraction hides implementation complexity.
Abstraction vs Encapsulation (Core Difference)
| Encapsulation | Abstraction |
|---|---|
| Hides internal data | Hides implementation details |
| Protects invariants | Defines behavior |
| Uses private fields | Uses interfaces / abstract classes |
| Focus: correctness | Focus: capability |
Encapsulation = protecting the object
Abstraction = describing the object
Abstraction Through Interfaces
An interface defines:
- What methods exist
- What behavior is promised
- Without saying how it’s implemented
It defines pure contract. It doesn't have constructor or fields.
Example: Payment System
We define an abstraction:
interface PaymentMethod {
void pay(double amount);
}
This says:
Any payment method must be able to process a payment of a given amount.
It does NOT say:
- How the payment works
- Whether it's credit card, PayPal, crypto, etc.
That’s abstraction.
Concrete Implementations
class CreditCardPayment implements PaymentMethod {
public void pay(double amount) {
System.out.println("Processing credit card payment of $" + amount);
}
}
class PayPalPayment implements PaymentMethod {
public void pay(double amount) {
System.out.println("Processing PayPal payment of $" + amount);
}
}
Each class:
- Has its own implementation
- Satisfies the same contract
Using the Abstraction
public class Checkout {
public void processPayment(PaymentMethod method) {
method.pay(100);
}
}
Notice something powerful:
Checkout does NOT know:
- What type of payment is used
- How payment is processed
It only knows the contract.
This is abstraction creating a boundary.
What is a Contract
A contract specifies:
- What inputs are expected
- What behavior is guaranteed
- What outputs will result
It does NOT describe internal algorithm.
Example contract for pay(amount):
- Precondition: amount > 0
- Postcondition: payment is processed or exception thrown
That’s a behavioral promise.
Abstract class vs Interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Methods | Abstract + Concrete | Mostly abstract (+ default/static) |
| Variables | Any type | Only constants |
| Inheritance | Single | Multiple |
| Constructor | Yes | No |
| Purpose | Base class | Behavior/contract |
Abstraction Creates Boundaries
Abstraction separates components.
For example:
[ Checkout System ]
|
| (PaymentMethod interface)
|
[ Payment Implementations ]
Checkout is independent from:
- Bank APIs
- Payment provider logic
- Security mechanisms
This reduces coupling.
If tomorrow you add:
class CryptoPayment implements PaymentMethod
Checkout does not change.
That’s the power of abstraction.
Encapsulation vs Abstraction — Same Example
Let’s analyze both principles in the Payment example.
Abstraction:
- Interface defines behavior (
pay) - Checkout depends on interface
- Implementation hidden
Encapsulation
Inside CreditCardPayment:
class CreditCardPayment implements PaymentMethod {
private String cardNumber;
public CreditCardPayment(String cardNumber) {
this.cardNumber = cardNumber;
}
public void pay(double amount) {
validateCard();
charge(amount);
}
private void validateCard() { }
private void charge(double amount) { }
}
Encapsulation:
cardNumberis private- Internal logic hidden
- Invariants protected
Abstraction:
- Only
pay()is visible to outside world
Deep Conceptual Difference
Think of abstraction as:
A role or capability description.
Think of encapsulation as:
A safety mechanism.
Abstraction answers: What can this object do?
Encapsulation answers: How does this object protect itself?
Real-World Analogy
Car Example
Abstraction:
You interact with:
- Steering wheel
- Pedals
- Gear shift
You don’t know how combustion works.
That’s abstraction.
Encapsulation:
Engine internals:
- Pistons
- Fuel injection
- Timing system
They are protected. You cannot randomly modify them.
That’s encapsulation.
Stronger Technical Example
Let’s build a logging system.
Step 1: Abstraction
interface Logger {
void log(String message);
}
Step 2: Implementations
class FileLogger implements Logger {
public void log(String message) {
System.out.println("Writing to file: " + message);
}
}
class DatabaseLogger implements Logger {
public void log(String message) {
System.out.println("Writing to database: " + message);
}
}
Step 3: System Using Abstraction
class Application {
private Logger logger;
public Application(Logger logger) {
this.logger = logger;
}
public void run() {
logger.log("Application started");
}
}
Application does not care:
- Where logs go
- How they are stored
- What storage system exists
It depends only on the abstraction.
Why Abstraction is Powerful
- Reduces complexity
- Enables substitution (polymorphism)
- Encourages loose coupling
- Makes systems extensible
- Improves testability (you can mock interfaces)
Quick Comparison Summary
| Concept | Purpose | Mechanism | Example |
|---|---|---|---|
| Encapsulation | Protect object integrity | private fields, controlled access | BankAccount balance |
| Abstraction | Define behavior and role | interfaces, abstract classes | PaymentMethod |
Final Key Insight
Encapsulation works inside a class.
Abstraction works between classes.
Encapsulation protects correctness.
Abstraction enables flexibility.
They complement each other.
Questions
Can We Instantiate an Abstraction?
No. You cannot create objects from:
- Interfaces
- Abstract classes
Instead, you must instantiate a concrete class that implements (for interfaces) or extends (for abstract classes) them.
This is because abstraction defines what must be done, not how it is done.
Abstract classes can have constructors, which are called when a subclass object is created. However, abstract classes themselves cannot be instantiated.
Can an interface contain variables?
- All interface variables are implicitly
public,static, andfinal - You cannot have
private,protected, or non-final instance variables in an interface. - They act like constants, not like fields that store per-object data.
When you need variables for interface, use abstract class instead.
Does abstract method and interface method must need to be implmented in child class?
There are cases where implementation is not required immediately:
If the child class is abstract
abstract class Dog extends Animal {
// No need to implement makeSound()
}
Default / concrete methods in interfaces (Java 8+)
Interfaces can now include implemented methods:
interface Vehicle {
default void start() {
System.out.println("Starting...");
}
}
→ The child class does NOT have to override it.
Final rule to remember
- Abstract method → must be implemented OR child must be abstract
- Interface method → must be implemented, unless:
- it's a default/static method, or
- the implementing class is abstract
What's the differences between interface in typescript and interface in OOP
The term “interface” shows up in both TypeScript and object-oriented programming (OOP), but they’re not exactly the same thing. The difference mainly comes down to purpose and how strictly they’re enforced.
Interface in TypeScript
In TypeScript, an interface is a compile-time construct used for type checking.
- Defines the shape of an object (properties, methods, types).
- Exists only during development — it disappears after compilation to JavaScript.
- Used for static typing, not runtime behavior.
- Can be merged and extended in flexible ways.
interface User {
name: string;
age: number;
greet(): void;
}
This just ensures that any object labeled User follows this structure.
Interface in OOP (e.g., Java, C#)
In traditional OOP languages, an interface is more like a contract that classes must implement.
- Defines what methods a class must implement, not how.
- Exists at runtime and compile time (depending on language).
- Enforces behavioral contracts.
- A class must explicitly implement the interface.
interface User {
void greet();
}
class Person implements User {
public void greet() {
System.out.println("Hello");
}
}
Main Differences
| Aspect | TypeScript Interface | OOP Interface |
|---|---|---|
| Purpose | Type checking | Behavioral contract |
| Exists at runtime? | ❌ No (erased after compile) | ✅ Yes (usually) |
| Enforces implementation | ❌ No real enforcement at runtime | ✅ Must implement |
| Flexibility | Very flexible (merging, partials) | More strict |
| Focus | Structure (shape of data) | Behavior (methods) |
The Big Idea
- TypeScript interface → “What does this object look like?”
- OOP interface → “What must this class be able to do?”
Subtle Overlap
TypeScript interfaces can describe methods too, so they sometimes feel like OOP interfaces, but:
- TypeScript doesn’t enforce anything at runtime.
- It’s more about developer tooling and safety, not strict contracts.