Chapter 06 of 26

Abstraction

When you book a cab on your phone, you tap "Book", pick a payment option and wait. You don't think about GPS triangulation, driver-matching algorithms or how the bank moves money. The app shows you only what you need and hides everything else. That idea, showing the essential and hiding the details, is called abstraction, and it is the second pillar of OOP we'll study after Encapsulation.

In this chapter you'll learn what abstraction really means, how it differs from encapsulation (a favourite interview question), and how Java, C++ and Python let you write abstract types. We'll only touch on abstract classes and interfaces here; the detailed comparison between them has its own chapter, Abstract Classes vs Interfaces.


What Is Abstraction?

Abstraction is the process of exposing only the essential features of an object (what it does) while hiding the implementation details (how it does it). The user of an abstraction works with a simplified model and does not depend on the internal details.

A few everyday examples:

  • Car: you use the steering wheel, accelerator and brake. You don't need to know how fuel injection or ABS works.

  • ATM: you see "Withdraw", "Balance", "Change PIN". The network protocol with your bank is hidden.

  • Java's Math.sqrt(): you call it and get a square root. Which algorithm it uses inside is not your problem.

In every case there is a simple outside view (the interface the user sees) and a complex inside view (the implementation). Abstraction is about designing that outside view well.

        What the user sees            What is hidden
   +--------------------------+    +----------------------------+
   |  pay(amount)             | →  |  UPI handshake, OTP check, |
   |  (one simple operation)  |    |  bank API call, retries,   |
   +--------------------------+    |  logging, error codes ...  |
                                   +----------------------------+

Why Do We Need Abstraction?

Abstraction is how humans manage complexity. A large program has thousands of classes; nobody can keep all their details in their head. Abstraction gives us these benefits:

  1. Simpler code for the user: callers deal with a few clear operations instead of every internal step.

  2. Freedom to change the implementation: if callers only depend on what an object does, you can rewrite how it does it without breaking them.

  3. Plug-in new variants: new types (a new payment method, a new shape) can be added without changing the code that uses the abstraction.

  4. Teamwork: one team can write code against an abstraction while another team builds the implementation.


Two Kinds of Abstraction

Textbooks usually describe two forms:

Kind

What is hidden

Example

Data abstraction

How data is stored and represented

A Stack type offers push() and pop(); you don't know whether it uses an array or a linked list

Control (process) abstraction

The sequence of steps an operation performs

Calling Collections.sort(list) instead of writing the sorting loops yourself

A plain method is already a small control abstraction: it gives a name to a sequence of steps. OOP goes further and lets you abstract over whole types, which is what the rest of this chapter is about.


Abstraction in Java's Own Library

You have used abstraction already, maybe without noticing. List in Java is an interface: it only says what a list can do (add, get, size ...). ArrayList and LinkedList are two different implementations.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListDemo {
    static void printAll(List<String> names) {   // works with ANY List
        for (String n : names) System.out.print(n + " ");
        System.out.println("(size " + names.size() + ")");
    }

    public static void main(String[] args) {
        List<String> a = new ArrayList<>(List.of("Asha", "Ravi"));
        List<String> b = new LinkedList<>(List.of("Meera", "Arjun", "Kiran"));
        printAll(a);
        printAll(b);
    }
}

Output:

Asha Ravi (size 2)
Meera Arjun Kiran (size 3)

printAll() never asks whether it got an array-backed or a node-based list. That is abstraction at work: the method depends on the abstract type List, not on a concrete class. This is also why experienced Java developers write List<String> x = new ArrayList<>() instead of ArrayList<String> x = ....


Tool 1: Abstract Classes and Abstract Methods

An abstract method is a method declared without a body; it states what must be done but not how. An abstract class is a class marked abstract that cannot be instantiated; it may contain abstract methods as well as normal fields, constructors and concrete methods.

Let's model shapes. Every shape has an area, but the formula depends on the shape. So area() is abstract, while describe() is common logic written once.

abstract class Shape {
    private final String name;

    Shape(String name) {
        this.name = name;
    }

    // WHAT every shape must do -- no body here
    abstract double area();

    // Shared, concrete behaviour written once
    void describe() {
        System.out.printf("%s with area %.2f%n", name, area());
    }
}

class Circle extends Shape {
    private final double radius;

    Circle(double radius) {
        super("Circle");
        this.radius = radius;
    }

    @Override
    double area() {
        return Math.PI * radius * radius;
    }
}

class Rectangle extends Shape {
    private final double length, width;

    Rectangle(double length, double width) {
        super("Rectangle");
        this.length = length;
        this.width = width;
    }

    @Override
    double area() {
        return length * width;
    }
}

public class ShapeDemo {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(2), new Rectangle(4, 5) };
        for (Shape s : shapes) {
            s.describe();
        }
    }
}

Output:

Circle with area 12.57
Rectangle with area 20.00

Step by step:

  1. Shape declares the abstract method area(). It is a promise: "every concrete shape will be able to compute its area".

  2. Circle and Rectangle extend Shape and keep that promise by overriding area(). (The extends keyword is covered in detail in Inheritance.)

  3. describe() lives in Shape and calls area() without knowing which shape it is. At run time the correct version runs. This is polymorphism, which gets its own chapter, Polymorphism.

The compiler enforces the rules of abstraction for you. You cannot create an object of an abstract class:

abstract class Shape {
    abstract double area();
}

public class AbstractError {
    public static void main(String[] args) {
        Shape s = new Shape();
    }
}
AbstractError.java:7: error: Shape is abstract; cannot be instantiated
        Shape s = new Shape();
                  ^
1 error

And a concrete subclass that forgets to implement the abstract method is rejected too:

class Triangle extends Shape {
    // forgot to write area()
}
Forgot.java:5: error: Triangle is not abstract and does not override abstract method area() in Shape
class Triangle extends Shape {
^
1 error

This is the real value: the "what" is checked at compile time, so you can't accidentally ship a shape without an area.


Tool 2: Interfaces

An interface is a contract: a named set of methods that a class promises to provide. A class implements an interface and supplies the bodies of its abstract methods.

Since Java 8 an interface may also contain default and static methods with bodies (and, since Java 9, private helper methods), but it can never have instance fields. Because they carry no per-object state, interfaces give the cleanest form of abstraction. Here is an online checkout that should accept UPI and cards today, and maybe wallets tomorrow:

interface PaymentMethod {
    boolean pay(double amount);   // the "what"
}

class UpiPayment implements PaymentMethod {
    private final String upiId;

    UpiPayment(String upiId) { this.upiId = upiId; }

    @Override
    public boolean pay(double amount) {
        // real code would call the bank's UPI API here
        System.out.println("Collect request of Rs." + amount + " sent to " + upiId);
        return true;
    }
}

class CardPayment implements PaymentMethod {
    private final String last4;

    CardPayment(String last4) { this.last4 = last4; }

    @Override
    public boolean pay(double amount) {
        System.out.println("Charging Rs." + amount + " to card ending " + last4);
        return true;
    }
}

class Checkout {
    // Checkout depends only on the abstraction, not on UPI or cards
    void placeOrder(double total, PaymentMethod method) {
        if (method.pay(total)) {
            System.out.println("Order confirmed.");
        }
    }
}

public class CheckoutDemo {
    public static void main(String[] args) {
        Checkout checkout = new Checkout();
        checkout.placeOrder(499.0, new UpiPayment("asha@okbank"));
        checkout.placeOrder(1299.0, new CardPayment("4821"));
    }
}

Output:

Collect request of Rs.499.0 sent to asha@okbank
Order confirmed.
Charging Rs.1299.0 to card ending 4821
Order confirmed.

Notice that Checkout has no if (type == "UPI") checks. To add a wallet, you write a new WalletPayment implements PaymentMethod class, and Checkout doesn't change at all. Designing code this way is the heart of the SOLID principles you'll meet later.

Quick orientation (the full comparison is in Abstract Classes vs Interfaces):

Use

When

Abstract class

Related classes share state (fields) or common code, and you want to force some methods to be filled in

Interface

You only want to describe a capability ("can pay", "can be compared") that unrelated classes may provide


Abstraction in C++ and Python

Other languages express the same idea with different syntax.

C++: pure virtual functions

C++ has no abstract keyword. A class becomes abstract when it has at least one pure virtual function, written with = 0.

#include <iostream>
#include <memory>
#include <numbers>
#include <vector>

class Shape {
public:
    virtual double area() const = 0;   // pure virtual: no body
    virtual ~Shape() = default;        // always virtual in a base class
};

class Circle : public Shape {
    double r;
public:
    explicit Circle(double r) : r(r) {}
    double area() const override { return std::numbers::pi * r * r; }
};

class Square : public Shape {
    double side;
public:
    explicit Square(double s) : side(s) {}
    double area() const override { return side * side; }
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(1.0));
    shapes.push_back(std::make_unique<Square>(3.0));
    for (const auto& s : shapes)
        std::cout << s->area() << '\n';
}

Output (compiled with g++ -std=c++23):

3.14159
9

Writing Shape s; gives error: cannot declare variable 's' to be of abstract type 'Shape'. The virtual destructor matters: objects are deleted through a Shape pointer, and without it the derived part would not be destroyed correctly (see Constructors & Destructors).

Python: the abc module

from abc import ABC, abstractmethod
import math


class Shape(ABC):
    @abstractmethod
    def area(self) -> float:
        ...


class Circle(Shape):
    def __init__(self, r: float):
        self.r = r

    def area(self) -> float:
        return math.pi * self.r ** 2


class Lazy(Shape):      # forgot to implement area()
    pass


print(round(Circle(2).area(), 2))
try:
    Lazy()
except TypeError as e:
    print("TypeError:", e)

Output (Python 3.14):

12.57
TypeError: Can't instantiate abstract class Lazy without an implementation for abstract method 'area'

Since Python is dynamically typed, the check happens when you try to create the object, not at compile time as in Java and C++.


Abstraction vs Encapsulation

These two are confused all the time because both "hide" something. The difference is what they hide and why.

Point

Abstraction

Encapsulation

Main question

What should the outside world see?

How do we protect the object's data?

Hides

Complexity and implementation choices

Internal state (fields) from direct access

Level

Design level: choosing the right operations

Implementation level: bundling data with methods and restricting access

Java tools

Abstract classes, interfaces

private fields, getters/setters, access modifiers

Example

PaymentMethod.pay() hides how UPI or cards work

BankAccount keeps balance private and allows changes only through deposit()/withdraw()

One-line version for interviews: abstraction hides complexity (design), encapsulation hides data (implementation). They work together: a well-encapsulated class is what makes a clean abstraction possible.


Common Mistakes

  • Thinking abstraction means "using the abstract keyword". Abstraction is a design idea. A simple class with a clear public method like sendEmail(to, body) is already an abstraction; abstract classes and interfaces are just tools that make it explicit.

  • Leaky abstractions. If PaymentMethod had a method like getUpiPin(), every caller would suddenly need to know about UPI. Keep implementation details out of the abstract type.

  • Abstracting too early. Creating an interface for a class that will only ever have one implementation, "just in case", adds files without adding flexibility. Introduce the abstraction when you actually see two variants or need to swap one for testing.

  • Forgetting the virtual destructor in C++ for an abstract base class that is deleted through a base pointer.

  • Expecting an abstract class to have no constructor. Abstract classes can (and often do) have constructors; they run when a subclass object is created, as Shape(String name) did above.


Interview Questions

What is abstraction? Give a real-life example.

Abstraction means exposing only what an object does and hiding how it does it. Example: a car's driver uses the steering wheel and pedals without knowing how the engine or brakes work internally. In code, a PaymentMethod interface with a single pay() method hides the details of UPI or card processing.

How is abstraction achieved in Java?

Mainly through abstract classes (which can mix abstract and concrete methods) and interfaces (contracts with no instance state; since Java 8 they may also hold default and static methods). More generally, any well-designed public method that hides its internal steps is also abstraction.

Can an abstract class have a constructor? Can we create its object?

It can have constructors, and they run when a subclass object is created (via super(...)). But you cannot create an object of the abstract class directly with new; the compiler reports "is abstract; cannot be instantiated". You can, however, have a reference of the abstract type pointing to a subclass object.

Can an abstract class have zero abstract methods?

Yes in Java. Marking a class abstract simply prevents direct instantiation, even if all its methods have bodies. In C++, by contrast, a class is abstract only if it has at least one pure virtual function.

Difference between abstraction and encapsulation?

Abstraction is a design-level idea: decide which operations to expose and hide complexity. Encapsulation is an implementation-level idea: bundle data with the methods that use it and restrict direct access to that data (e.g. private fields). Abstraction hides complexity; encapsulation hides data.

How do you make a class abstract in C++?

Declare at least one pure virtual function, e.g. virtual double area() const = 0;. Such a class cannot be instantiated, and a derived class stays abstract until it overrides all pure virtual functions.


Summary

  • Abstraction shows what an object does and hides how it does it.

  • It reduces complexity, lets you change implementations freely and add new variants without touching existing callers.

  • Data abstraction hides representation; control abstraction hides steps.

  • Java tools: abstract classes (cannot be instantiated, can mix abstract and concrete members) and interfaces (contracts with no instance fields). C++ uses pure virtual functions (= 0); Python uses abc.ABC and @abstractmethod.

  • Write code against the abstract type (List, PaymentMethod), not the concrete class.

  • Abstraction hides complexity; encapsulation hides data.

Abstract classes only become useful when other classes extend them. In the next chapter, Inheritance, we'll study exactly how a class reuses and builds on another class.