OOP Fundamentals

Abstraction

Hide complex implementation details and expose only essential features. Show WHAT an object does, not HOW it does it.

10 min readEssential

1What is Abstraction?

Real-World Analogy
Car Dashboard

You see speedometer, fuel gauge, and steering wheel. You do not see the engine, transmission, or fuel injection system. The dashboard abstractsthe complex mechanics and shows only what you need.

ATM Machine

You insert card, enter PIN, get cash. You do not see bank servers, network protocols, or transaction processing. The ATM abstracts all complexity behind simple operations.

Abstraction is the process of hiding implementation details while exposing only the essential features. It answers the question: What should this do?without specifying How does it do it?

Abstraction Layers

User Interface
click(), submit()
^
Business Logic
processPayment(), validateOrder()
^
Data Access Layer
save(), find(), delete()
^
Database / External APIs
SQL, HTTP, TCP/IP...
Each layer abstracts the complexity of layers below it

2Abstract Classes vs Interfaces

Abstract Class
  • ✓ Can have abstract AND concrete methods
  • ✓ Can have instance variables
  • ✓ Can have constructors
  • ✓ Supports access modifiers
  • ✗ Single inheritance only
  • Use when: Classes share common code
Interface
  • ✓ Only abstract methods (before Java 8)
  • ✓ Can have default methods (Java 8+)
  • ✓ All fields are public static final
  • ✓ Multiple inheritance allowed
  • ✗ No constructors
  • Use when: Define a contract/capability
When to Use Which?
  • Abstract Class: When classes share common code AND state (IS-A relationship)
  • Interface: When you want to define a capability that unrelated classes can implement (CAN-DO relationship)
  • Example: Animal is an abstract class. Flyable is an interface (Bird, Plane, Superman can fly)

3Implementation

Payment System - Abstraction Example
// ========== Abstract Class ==========
public abstract class PaymentProcessor {
    protected String merchantId;
    protected double transactionFee;

    public PaymentProcessor(String merchantId) {
        this.merchantId = merchantId;
    }

    // Abstract method - WHAT to do (no HOW)
    public abstract boolean processPayment(double amount);

    // Abstract method
    public abstract void refund(String transactionId);

    // Concrete method - shared implementation
    public double calculateFee(double amount) {
        return amount * transactionFee;
    }

    // Template method
    public final void executeTransaction(double amount) {
        System.out.println("Starting transaction...");
        validateMerchant();
        if (processPayment(amount)) {
            System.out.println("Payment successful!");
            logTransaction(amount);
        } else {
            System.out.println("Payment failed!");
        }
    }

    private void validateMerchant() {
        System.out.println("Validating merchant: " + merchantId);
    }

    private void logTransaction(double amount) {
        System.out.println("Logged transaction of $" + amount);
    }
}

// ========== Concrete Implementation 1 ==========
public class CreditCardProcessor extends PaymentProcessor {
    private String apiKey;

    public CreditCardProcessor(String merchantId, String apiKey) {
        super(merchantId);
        this.apiKey = apiKey;
        this.transactionFee = 0.029; // 2.9%
    }

    @Override
    public boolean processPayment(double amount) {
        System.out.println("Processing credit card payment of $" + amount);
        // Complex credit card logic hidden here
        // - Connect to payment gateway
        // - Encrypt card data
        // - Handle 3D Secure
        // - Process with bank
        return true;
    }

    @Override
    public void refund(String transactionId) {
        System.out.println("Refunding credit card transaction: " + transactionId);
    }
}

// ========== Concrete Implementation 2 ==========
public class UPIProcessor extends PaymentProcessor {
    public UPIProcessor(String merchantId) {
        super(merchantId);
        this.transactionFee = 0.0; // No fee for UPI
    }

    @Override
    public boolean processPayment(double amount) {
        System.out.println("Processing UPI payment of Rs." + amount);
        // Complex UPI logic hidden here
        // - Generate QR code or collect VPA
        // - Send request to NPCI
        // - Wait for user approval
        return true;
    }

    @Override
    public void refund(String transactionId) {
        System.out.println("Initiating UPI refund: " + transactionId);
    }
}

// ========== Usage ==========
public class Main {
    public static void main(String[] args) {
        // User does not need to know HOW payment works
        PaymentProcessor processor = new CreditCardProcessor("MERCH123", "api_key");
        processor.executeTransaction(100.00);

        System.out.println();

        processor = new UPIProcessor("MERCH123");
        processor.executeTransaction(500.00);
    }
}
Output:
Starting transaction...
Validating merchant: MERCH123
Processing credit card payment of $100.0
Payment successful!
Logged transaction of $100.0

Starting transaction...
Validating merchant: MERCH123
Processing UPI payment of Rs.500.0
Payment successful!
Logged transaction of $500.0

4Abstraction vs Encapsulation

AspectAbstractionEncapsulation
FocusWHAT (design level)HOW (implementation level)
PurposeHide complexityHide data
Achieved viaAbstract classes, interfacesAccess modifiers, getters/setters
ExamplePaymentProcessor hides implementationBankAccount hides balance variable
Working Together
Abstraction and Encapsulation complement each other. Abstraction defines WHAT operations are available (interface), while Encapsulation hides HOW those operations work internally (implementation).

5Interview Questions

What is abstraction and why is it important?
Abstraction hides complex implementation details and exposes only essential features. Importance: 1) Reduces complexity - users see simplified interface, 2) Promotes loose coupling - changes in implementation don't affect users, 3) Enables polymorphism - code works with abstract types, 4) Improves maintainability - implementation can change without breaking clients.
Can you instantiate an abstract class?
No. Abstract classes cannot be instantiated directly because they are incomplete - they may have abstract methods without implementation. You must create a concrete subclass that implements all abstract methods. However, abstract classes CAN have constructors which are called when instantiating subclasses.
What is the difference between abstraction and encapsulation?
Abstraction is about WHAT - hiding complexity by showing only essential features (design level). Encapsulation is about HOW - hiding data by bundling it with methods and restricting access (implementation level). Abstraction: 'You can make payment'. Encapsulation: 'Balance field is private, use getBalance()'.

6Key Takeaways

1Abstraction hides complexity, shows only essential features.
2Achieved through abstract classes and interfaces.
3Abstract class: partial implementation + abstract methods. Single inheritance.
4Interface: contract/capability. Multiple inheritance allowed.
5Abstraction = WHAT, Encapsulation = HOW. They complement each other.
6Enables writing code against interfaces, not implementations.