B3.2.3 Abstraction in OOP
HL onlyCommand term: Explain1. 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.
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.
Checkout (never changes)
The plugged-in module
4. Abstract class or interface? (Java)
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.
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.
| LibraryItem member | Kind | Why |
|---|
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.
Think about it
- Why is
late_fee()concrete whiledaily_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
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.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
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):
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
Model solution
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)
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):
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
Model solution
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)
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):
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
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.
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:
- Explain abstraction as hiding complexity and exposing only the essential features needed to use an object.
- Explain the significance of abstraction in developing modular code fragments that can be built, tested and replaced independently.
- Construct abstract classes with abstract methods that establish a common interface every subclass must implement.
- Explain why an abstract class cannot be instantiated, and what happens when a subclass fails to implement an abstract method.
- 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 class | Abstract class | Interface (Java) | |
|---|---|---|---|
| Can be instantiated? | yes | no | no |
| Abstract methods? | no | zero or more | normally all of them |
| Attributes and constructors? | yes | yes | no (constants only) |
| A class can use how many? | extends 1 | extends 1 | implements many |
| Purpose | a real, usable thing | shared code plus a contract | a 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]
2. Explain why an abstract class cannot be instantiated. [2]
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]
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 ** 24. 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]
5. Distinguish between an abstract class and an interface in Java. [3]
6. A subclass of an abstract class does not implement one of the abstract methods. Outline what happens in Java and in Python. [2]