Home › Theme B › B3 › B3.2 › B3.2.3

B3.2.3 Abstraction in OOP

HL onlyCommand term: Explain

1. Peel back the layers of abstraction

A shop's checkout only needs to say "pay this amount". Step down through the layers and see how much detail is hidden below that one line, and which layer each kind of programmer needs to know about.

2. The abstract class contract

LibraryItem is abstract: it declares daily_fee() and describe() but does not implement them. Choose which methods the new subclass Ebook implements, and what the program tries to create. Then compare Python and Java.

Ebook implements:   Create:

Python

Java

3. Modular plug-ins: swap the module, keep the checkout

The checkout is written against the abstract PaymentMethod only. Plug in different payment modules: the checkout code never changes, and each module can be written and tested by a different developer.

Module:   Basket total 40.00

Checkout (never changes)

The plugged-in module

4. Abstract class or interface? (Java)

Example:

5. Flip-card deck

Click to flip. Say the answer before you flip.

6. Abstract or concrete?

Decide how each part of the design should be modelled. Streaks of 3+ score double.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: can it be created?

Python. Does the last line create an object, or raise a TypeError? A wrong answer costs 3 seconds.

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 7, task 3 (HL). Nobody should ever create a plain LibraryItem: every real item is a Book, a DVD or, from today, an Ebook. Make LibraryItem an abstract class whose abstract methods form the contract every item type must fulfil, while the shared calculations stay concrete in the base class.
LibraryItem memberKindWhy

Expected output

The wording of the "Broken" message depends on your Python version; versions before 3.12 say Can't instantiate abstract class Broken with abstract method describe.

Cannot create a plain LibraryItem Broken: Can't instantiate abstract class Broken without an implementation for abstract method 'describe' Dune by Herbert 0.8 Up (96 min) 4.0 Emma [ebook, 3 MB] 0.0 12.0

Think about it

  • Why is late_fee() concrete while daily_fee() is abstract?
  • Python only reports a missing method when you try to create an object; Java reports it when the class is compiled. Which is safer for a large team, and why?
  • A new developer adds class Map(LibraryItem). Without reading any other code, how do they know which methods they must write?

Check my code

    Next (B3.2.4): composition and aggregation. A Library has items and members; a Loan is made of a book and a member.

    Practical tasks

    Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    Task 1: An abstract Shape

    Use the abc module to make Shape an abstract class with an abstract method area() and a normal method describe() that uses it. Show that Shape() cannot be created, but Rect(2, 3) can.

    Starter file (write your code where it says pass # your code here):

    File: b3_2_3_average.py
    from abc import ABC, abstractmethod
    
    class Shape(ABC):
        pass  # your code here
    
    class Rect(Shape):
        pass  # your code here
    
    # ---- tests ----
    print(Rect(2, 3).describe())
    try:
        Shape()
    except TypeError as e:
        print("TypeError:", e)
    

    Expected output when your code is correct:

    Rect with area 6
    TypeError: Can't instantiate abstract class Shape without an implementation for abstract method 'area'
    Hint
    A class with an @abstractmethod cannot be instantiated until a subclass implements it.
    Model solution
    File: b3_2_3_average_solution.py
    from abc import ABC, abstractmethod
    
    class Shape(ABC):
        @abstractmethod
        def area(self):
            pass
    
        def describe(self):
            return f"{type(self).__name__} with area {self.area()}"
    
    class Rect(Shape):
        def __init__(self, w, h):
            self.w, self.h = w, h
        def area(self):
            return self.w * self.h
    
    # ---- tests ----
    print(Rect(2, 3).describe())
    try:
        Shape()
    except TypeError as e:
        print("TypeError:", e)
    
    Moderate

    Task 2: Payments with a template method

    Write an abstract class PaymentMethod with a concrete method pay(amount) that checks the amount is positive, calls the abstract method authorise(amount), and returns a receipt string. Implement Card (limit 2 000) and Wallet (has a balance that decreases). The order of steps is fixed in the parent; only authorise varies.

    Starter file (write your code where it says pass # your code here):

    File: b3_2_3_moderate.py
    from abc import ABC, abstractmethod
    
    class PaymentMethod(ABC):
        pass  # your code here
    
    class Card(PaymentMethod):
        pass  # your code here
    
    class Wallet(PaymentMethod):
        pass  # your code here
    
    # ---- tests ----
    w = Wallet(100)
    for method, amount in [(Card(), 150), (Card(), 2500), (w, 60), (w, 60), (w, -3)]:
        print(method.pay(amount))
    print("wallet left:", w.balance)
    

    Expected output when your code is correct:

    paid 150 by Card
    declined by Card
    paid 60 by Wallet
    declined by Wallet
    rejected: amount must be positive
    wallet left: 40
    Hint
    The abstract parent controls the algorithm; children fill in one step.
    Model solution
    File: b3_2_3_moderate_solution.py
    from abc import ABC, abstractmethod
    
    class PaymentMethod(ABC):
        def pay(self, amount):
            if amount <= 0:
                return "rejected: amount must be positive"
            if not self.authorise(amount):
                return f"declined by {type(self).__name__}"
            return f"paid {amount} by {type(self).__name__}"
    
        @abstractmethod
        def authorise(self, amount):
            pass
    
    class Card(PaymentMethod):
        LIMIT = 2000
        def authorise(self, amount):
            return amount <= Card.LIMIT
    
    class Wallet(PaymentMethod):
        def __init__(self, balance):
            self.balance = balance
        def authorise(self, amount):
            if amount > self.balance:
                return False
            self.balance -= amount
            return True
    
    # ---- tests ----
    w = Wallet(100)
    for method, amount in [(Card(), 150), (Card(), 2500), (w, 60), (w, 60), (w, -3)]:
        print(method.pay(amount))
    print("wallet left:", w.balance)
    
    Challenging

    Task 3: Abstract sensors

    Write an abstract Sensor class with abstract methods read_raw() and convert(raw), an abstract property unit, and a concrete method reading() that returns e.g. "22.5 °C". It must also keep the last 5 readings and offer average(). Implement TempSensor (raw values 0 to 1023 map to −40 to 85 °C) and LightSensor (raw × 2 lux). Use fixed lists of raw values to simulate the hardware.

    Starter file (write your code where it says pass # your code here):

    File: b3_2_3_challenging.py
    from abc import ABC, abstractmethod
    
    class Sensor(ABC):
        pass  # your code here
    
    class TempSensor(Sensor):
        pass  # your code here
    
    class LightSensor(Sensor):
        pass  # your code here
    
    # ---- tests ----
    t = TempSensor([0, 512, 1023, 500, 520, 510, 530])
    print([t.reading() for _ in range(7)])
    print(t.history, t.average())
    l = LightSensor([100, 250])
    print(l.reading(), l.reading(), l.average())
    

    Expected output when your code is correct:

    ['-40.0 °C', '22.6 °C', '85.0 °C', '21.1 °C', '23.5 °C', '22.3 °C', '24.8 °C']
    [85.0, 21.1, 23.5, 22.3, 24.8] 35.3
    200 lux 500 lux 350.0
    Hint
    Put everything the sensors share in the abstract parent.
    Model solution

    Note: the model makes read_raw concrete in the parent because both simulated sensors read from a list in the same way. With real hardware, each subclass would override it.

    File: b3_2_3_challenging_solution.py
    from abc import ABC, abstractmethod
    
    class Sensor(ABC):
        def __init__(self, raw_values):
            self._raw = iter(raw_values)
            self.history = []
    
        @abstractmethod
        def convert(self, raw):
            pass
    
        @property
        @abstractmethod
        def unit(self):
            pass
    
        def read_raw(self):
            return next(self._raw)
    
        def reading(self):
            value = round(self.convert(self.read_raw()), 1)
            self.history = (self.history + [value])[-5:]
            return f"{value} {self.unit}"
    
        def average(self):
            return round(sum(self.history) / len(self.history), 1)
    
    class TempSensor(Sensor):
        unit = "°C"
        def convert(self, raw):
            return -40 + raw * 125 / 1023
    
    class LightSensor(Sensor):
        unit = "lux"
        def convert(self, raw):
            return raw * 2
    
    # ---- tests ----
    t = TempSensor([0, 512, 1023, 500, 520, 510, 530])
    print([t.reading() for _ in range(7)])
    print(t.history, t.average())
    l = LightSensor([100, 250])
    print(l.reading(), l.reading(), l.average())
    

    Learning objectives

    By the end of this page you should be able to:

    1. Explain abstraction as hiding complexity and exposing only the essential features needed to use an object.
    2. Explain the significance of abstraction in developing modular code fragments that can be built, tested and replaced independently.
    3. Construct abstract classes with abstract methods that establish a common interface every subclass must implement.
    4. Explain why an abstract class cannot be instantiated, and what happens when a subclass fails to implement an abstract method.
    5. Distinguish between abstract classes, concrete classes and Java interfaces.

    What abstraction means

    Abstraction is showing only the essential features of something and hiding the details that are not needed to use it. A driver uses a steering wheel and pedals, not the engine's fuel-injection timing. In OOP, a class offers methods such as pay(amount); the code that calls it does not need to know how the payment really happens. (Abstraction was introduced as a computational thinking skill in B1.1.)

    Abstraction and encapsulation work together: abstraction decides what to show (the essential interface); encapsulation is how the rest is hidden (private attributes and methods).

    Abstraction and modularity

    • Code is split into modules that talk to each other only through agreed interfaces.
    • Each module can be developed and tested separately, often by different people or teams, as long as it keeps to the interface.
    • A module can be replaced (a new payment provider) without changing the code that uses it.
    • Programmers work at the level that matters to them: the checkout developer thinks about baskets, not bank networks.

    Abstract classes

    from abc import ABC, abstractmethod             # Python
    
    class LibraryItem(ABC):
        def __init__(self, title):
            self._title = title
    
        @abstractmethod
        def daily_fee(self):                         # declared, not implemented
            pass
    
        def late_fee(self, days):                    # concrete: shared by every subclass
            return round(days * self.daily_fee(), 2)
    
    abstract class LibraryItem {                     // Java
        protected String title;
        LibraryItem(String title) { this.title = title; }
        abstract double dailyFee();                  // no body
        double lateFee(int days) { return days * dailyFee(); }
    }
    • An abstract class cannot be instantiated. It exists to be extended, and represents a general idea (Shape, PaymentMethod) that never exists on its own.
    • An abstract method has a signature but no body. Every concrete subclass must override it, so the abstract class establishes a common interface (a contract) for all its subclasses.
    • An abstract class can also contain attributes, constructors and concrete methods that subclasses inherit.
    • Java checks the contract at compile time ("is not abstract and does not override abstract method"). Python checks when you try to create an object (TypeError).

    Java interfaces

    A Java interface lists method signatures that a class promises to provide (class Book implements Lendable). It has no instance attributes or constructors. A class can extend only one class but can implement many interfaces.

    Concrete classAbstract classInterface (Java)
    Can be instantiated?yesnono
    Abstract methods?nozero or morenormally all of them
    Attributes and constructors?yesyesno (constants only)
    A class can use how many?extends 1extends 1implements many
    Purposea real, usable thingshared code plus a contracta contract only

    Use the 中文 button at the top to show or hide the Chinese terms.

    Term中文Meaning

    Choose an answer. You get instant feedback.

    Score: 0 /

    Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.

    1. Define the term abstraction in the context of OOP. [2]

    Showing only the essential features / interface of an object or system [1] while hiding the unnecessary implementation details from the code that uses it [1].

    2. Explain why an abstract class cannot be instantiated. [2]

    It may contain abstract methods that have no implementation / body [1], so an object of that class could not respond to those method calls; it represents a general concept that only exists through its concrete subclasses [1].

    3. Construct an abstract class Shape with an abstract method area() and a concrete method describe() that returns a string containing the area. Then construct a concrete subclass Circle. [4]

    Shape declared abstract (ABC / abstract keyword) [1]; area() declared abstract with no implementation [1]; concrete describe() that calls area() [1]; Circle extends Shape, stores the radius and overrides area() [1].
    from abc import ABC, abstractmethod
    import math
    
    class Shape(ABC):
        @abstractmethod
        def area(self):
            pass
        def describe(self):
            return "Area: " + str(round(self.area(), 2))
    
    class Circle(Shape):
        def __init__(self, r):
            self.r = r
        def area(self):
            return math.pi * self.r ** 2

    4. A team of five is building a payment system that must support several payment providers. Explain how abstraction supports the modular development of this system. [4]

    An abstract PaymentMethod class defines the common interface (e.g. pay(amount)) that every provider must implement [1]; the checkout code is written against this interface only, so it does not depend on any provider's details [1]; different developers can build and test each provider module independently / in parallel [1]; providers can be added or replaced without changing the checkout code [1].

    5. Distinguish between an abstract class and an interface in Java. [3]

    An abstract class can contain attributes, constructors and concrete methods as well as abstract methods; an interface (normally) contains only method signatures / constants [1]; a class can extend only one abstract class but can implement many interfaces [1]; an abstract class shares code as well as a contract, while an interface defines a contract only [1].

    6. A subclass of an abstract class does not implement one of the abstract methods. Outline what happens in Java and in Python. [2]

    Java: the subclass does not compile unless it is itself declared abstract [1]; Python: the class is defined, but creating an object of it raises a TypeError at run time [1].