Learn
B3.2.3 | ABSTRACTION IN OOP (HL ONLY)
01 | ASK FOR A RESULT, NOT EVERY INTERNAL STEP
When you press Print in an application, you choose the document and printer. You do not normally provide instructions for moving the print head, feeding paper or communicating with the hardware. The application gives you a useful operation while leaving unnecessary implementation details behind that operation.
In object-oriented programming, abstraction means presenting the essential features of an object through an appropriate interface while leaving out implementation details that its users do not need. The caller concentrates on what an operation does, rather than every instruction used to achieve it.
Abstraction does not mean being vague. A good interface clearly states the required inputs, expected result and relevant rules. The implementation can then change while those expectations remain stable.
02 | A SCHOOL NOTIFICATION PROBLEM
A school app needs to preview messages for different delivery channels. An email preview begins with Email:, while a screen preview begins with Screen:. Both identify the recipient. The preview page should not need to know how each channel builds its message.
We will model this with an abstract Notification class. It describes the common operations and contains reusable code. EmailNotification and ScreenNotification provide the channel-specific formatting. No messages are sent: every example returns and prints simulated preview text.
The distinction matters. A classroom string-formatting example is not an email service. A real sending operation would also need authentication, delivery error handling and other requirements outside this lesson.
03 | WHAT IS AN INTERFACE HERE?
An interface, in the general design sense, is the set of operations and expectations through which other code uses an object. For our previews, the important operation is preview(text): give it message text and receive a complete preview string.
| Caller needs to know | Caller need not know |
|---|---|
| Call preview(text) | Exactly how a channel constructs its prefix |
| Supply a string such as Meeting at 16:00 | Where each intermediate string is stored |
| Use the returned preview string | Which subclass implements format_message |
| Expect no real sending or state change | The internal order of formatting helpers beyond the contract |
This general meaning of interface is broader than Java’s interface keyword. An abstract class can establish a common interface without being declared as a Java interface. We will distinguish the language features later.
04 | THREE IDEAS THAT WORK TOGETHER
| Idea | Main question | In our example |
|---|---|---|
| Abstraction | What operations and essential behaviour should callers see? | Request a preview without knowing channel formatting |
| Encapsulation | How are state and behaviour organised, and access controlled? | Store recipient state and manage its use within objects |
| Polymorphism | How can a common call run different implementations? | format_message runs the email or screen version |
These ideas support each other, but they are not synonyms. Making every attribute private does not automatically produce a useful abstraction. A class could hide its fields yet expose dozens of confusing methods that force callers to understand its internal representation.
Aim for an interface that matches the problem: preview a notification. Then use encapsulation and polymorphism to implement that design cleanly.
05 | WHY NOT CREATE A GENERAL NOTIFICATION?
We know every notification needs a channel-specific formatted message. However, a general Notification has no chosen channel. Inventing a default such as an empty string could hide a missing implementation and produce an incomplete preview without explaining the problem.
An abstract class represents a general concept that should not be instantiated directly. It can require concrete subclasses to supply particular operations. In our model, Notification describes what all channels share, while each usable channel must provide format_message.
Abstract is a design choice, not a claim that the class is useless. It can still contain state, an initializer and fully implemented methods that concrete objects reuse.
06 | READ THE CLASS DESIGN
This overview uses Python-style method names. The Java version uses recipientLabel and formatMessage. Italics identify the abstract class and abstract operation. Visibility and initializer details are omitted here so the diagram focuses on the relationship.
Both concrete classes inherit from Notification. The base class defines the common shape of the solution; the subclasses fill in the variable part.
07 | PYTHON: DECLARE AN ABSTRACT BASE CLASS
from abc import ABC, abstractmethod
class Notification(ABC):
@abstractmethod
def format_message(self, text):
pass
abc is part of Python’s standard library. ABC supplies abstract-base-class machinery, and @abstractmethod marks an operation that must be implemented before an ordinary subclass can be instantiated. The decorator is the line beginning with @ immediately above the method.
pass is an empty statement used here as a placeholder body. It does not create a usable default formatter. A normal attempt to instantiate Notification raises TypeError because format_message is still abstract.
Abstraction as a design principle does not require this exact syntax. ABC is one way to make an intended requirement explicit and enforce the instantiation rule in Python.
08 | AN ABSTRACT CLASS CAN HAVE AN INITIALIZER
class Notification(ABC):
def __init__(self, recipient):
if not isinstance(recipient, str) or not recipient.strip():
raise ValueError("Recipient must be non-empty text")
self.recipient = recipient.strip()
@abstractmethod
def format_message(self, text):
pass
This is an expanded version of the class, not a second class to add beneath the previous one. The initializer checks that the recipient is non-empty text and stores a trimmed version on the object. strip removes whitespace from the beginning and end.
When a concrete subclass inherits this initializer, it prepares that subclass instance. There is no separate Notification object inside it. Abstract classes can initialize shared state even though they cannot be constructed directly.
09 | SHARE THE PART THAT IS ALREADY KNOWN
from abc import ABC, abstractmethod
class Notification(ABC):
def __init__(self, recipient):
if not isinstance(recipient, str) or not recipient.strip():
raise ValueError("Recipient must be non-empty text")
self.recipient = recipient.strip()
def recipient_label(self):
return f"To: {self.recipient}"
@abstractmethod
def format_message(self, text):
pass
def preview(self, text):
return self.recipient_label() + "\n" + self.format_message(text)
recipient_label is a concrete method: it already has working instructions. preview is also concrete. It combines the recipient label, a newline and the channel-specific formatted message. The escape sequence \n produces a line break in the returned string.
The base class does not know the channel, but it knows the sequence needed to build a preview. It calls self.format_message(text), relying on a concrete subclass to supply that part. This is a small example of organising a reusable algorithm around a variable step.
The contract expects text to be a string. The ABC declaration enforces that an abstract name is implemented before instantiation; it does not automatically validate every input or result.
10 | IMPLEMENT A CONCRETE SUBCLASS
class EmailNotification(Notification):
def format_message(self, text):
return "Email: " + text
email = EmailNotification("Maya")
print(email.preview("Meeting at 16:00"))
# To: Maya
# Email: Meeting at 16:00
EmailNotification provides the required formatter, so it is concrete and can be instantiated. It inherits the initializer, recipient_label and preview. The only new behaviour is the channel prefix.
Follow the call: email.preview runs the inherited preview method; inside that method, self refers to the EmailNotification object; therefore self.format_message runs EmailNotification.format_message. Shared code and specialised code cooperate in one object.
11 | ADD ANOTHER CONCRETE IMPLEMENTATION
class EmailNotification(Notification):
def format_message(self, text):
return "Email: " + text
class ScreenNotification(Notification):
def format_message(self, text):
return "Screen: " + text
Both classes return strings from the same calling pattern, format_message(text). ScreenNotification does not duplicate the code that adds the recipient label or joins the two lines. It only supplies the behaviour that differs.
This makes the design modular: one unit owns the common preview construction, while smaller class definitions own channel-specific formatting. If the recipient label changes, there is one shared implementation to edit instead of a copy in every channel.
12 | WHAT IF A SUBCLASS IS INCOMPLETE?
class UnfinishedNotification(Notification):
pass
try:
item = UnfinishedNotification("Sam")
except TypeError:
print("Cannot create: format_message is still abstract")
Defining this subclass is permitted. Creating an instance is blocked because it still has an unimplemented abstract method. The failure occurs when UnfinishedNotification("Sam") is attempted, before the caller can produce an incomplete preview.
The exact Python error text can vary between versions; the important outcome is TypeError and the missing abstract implementation. A subclass can intentionally remain abstract if a later specialised subclass will complete it.
13 | TRACE CREATION AND METHOD CALLS
Predict which constructions fail and which implementation supplies the formatted message. An abstract-class failure is not a partially created usable notification. The trace also shows that an inherited concrete method can call a subclass method.
14 | A COMPLETE PYTHON PROGRAM
Save this as abstraction_demo.py and click Run in your editor. The import, abstract class and concrete subclasses come before the objects are created. The final function works with compatible notifications without choosing a different call for each channel.
from abc import ABC, abstractmethod
class Notification(ABC):
def __init__(self, recipient):
if not isinstance(recipient, str) or not recipient.strip():
raise ValueError("Recipient must be non-empty text")
self.recipient = recipient.strip()
def recipient_label(self):
return f"To: {self.recipient}"
@abstractmethod
def format_message(self, text):
pass
def preview(self, text):
return self.recipient_label() + "\n" + self.format_message(text)
class EmailNotification(Notification):
def format_message(self, text):
return "Email: " + text
class ScreenNotification(Notification):
def format_message(self, text):
return "Screen: " + text
def show_previews(notifications, text):
for notification in notifications:
print(notification.preview(text))
notifications = [EmailNotification("Maya"), ScreenNotification("Leo")]
show_previews(notifications, "Meeting at 16:00")
The output contains four lines: To: Maya, Email: Meeting at 16:00, To: Leo, Screen: Meeting at 16:00. No external service is contacted. The abstract base makes the required operation visible; polymorphism chooses the concrete formatter when preview calls it.
15 | JAVA: ABSTRACT CLASS AND METHOD
abstract class Notification {
private final String recipient;
public Notification(String recipient) {
this.recipient = recipient;
}
public String recipientLabel() {
return "To: " + recipient;
}
public abstract String formatMessage(String text);
public String preview(String text) {
return recipientLabel() + "\n" + formatMessage(text);
}
}
Java uses the abstract keyword on the class and the unimplemented method. The method declaration ends with a semicolon instead of a method body. The constructor, recipientLabel and preview all have working implementations.
This short version assumes a valid recipient so the abstract syntax is easy to see. The complete Java program below adds validation. new Notification("Maya") is a compile-time error because Notification is abstract. It is not a normal construction followed by an error only when the method is called.
16 | JAVA: IMPLEMENT THE REQUIRED METHOD
class EmailNotification extends Notification {
public EmailNotification(String recipient) {
super(recipient);
}
@Override
public String formatMessage(String text) {
return "Email: " + text;
}
}
The constructor calls the superclass constructor to initialize the shared recipient state. Constructors are not inherited in Java. @Override helps the compiler verify that formatMessage implements the inherited operation with the correct signature.
A non-abstract subclass must implement all remaining abstract methods, either itself or through an inherited concrete implementation. If it does not, compilation fails. Declaring the subclass abstract allows it to leave work for a later subclass.
17 | A COMPLETE JAVA PROGRAM
Save this as AbstractionExample.java. Only AbstractionExample is public; the other classes share the file for the exercise. Run its main method in your Java editor. The output matches the complete Python example.
abstract class Notification {
private final String recipient;
public Notification(String recipient) {
if (recipient == null || recipient.trim().isEmpty()) {
throw new IllegalArgumentException("Recipient must be non-empty text");
}
this.recipient = recipient.trim();
}
public String recipientLabel() {
return "To: " + recipient;
}
public abstract String formatMessage(String text);
public String preview(String text) {
return recipientLabel() + "\n" + formatMessage(text);
}
}
class EmailNotification extends Notification {
public EmailNotification(String recipient) {
super(recipient);
}
@Override
public String formatMessage(String text) {
return "Email: " + text;
}
}
class ScreenNotification extends Notification {
public ScreenNotification(String recipient) {
super(recipient);
}
@Override
public String formatMessage(String text) {
return "Screen: " + text;
}
}
public class AbstractionExample {
public static void showPreviews(Notification[] items, String text) {
for (Notification item : items) {
System.out.println(item.preview(text));
}
}
public static void main(String[] args) {
Notification[] items = {
new EmailNotification("Maya"),
new ScreenNotification("Leo")
};
showPreviews(items, "Meeting at 16:00");
}
}
Notification[] is an array of references declared using the common abstract type. Its elements refer to concrete EmailNotification and ScreenNotification objects. Abstract types can be used for variables, parameters and collections even though you cannot instantiate the abstract class itself.
18 | A COMMON TYPE DOES NOT MEAN A GENERAL OBJECT
Notification item = new EmailNotification("Maya");
System.out.println(item.preview("Hello"));
Place these statements inside main with the preceding Java classes available. The declared type is Notification, and the actual object is EmailNotification. The reference provides access to the common operations, while runtime dispatch selects the concrete formatMessage implementation.
There is no contradiction in a variable having an abstract declared type. The restriction applies to directly constructing an instance of that abstract class. A variable can refer to a concrete object that meets the abstract class’s requirements.
19 | ABSTRACT CLASS OR INTERFACE?
| Feature | Abstract class | Java interface |
|---|---|---|
| Main role | Model a shared base with required operations and possibly common state/behaviour | Describe a capability or contract that implementing classes provide |
| Instance state and construction | Can hold instance fields and have constructors | Has no per-instance fields or constructors; its fields are constants |
| Implemented methods | Can contain concrete methods alongside abstract ones | Can contain default, static and private methods as well as abstract declarations |
| Multiple relationships in Java | A class extends at most one class | A class can implement multiple interfaces |
An abstract class suits our example because it stores common recipient state and reuses preview construction. A Java interface could instead express a general Previewable capability across otherwise unrelated classes.
Do not memorise the outdated claim that interfaces never contain method implementations. Focus on what each tool offers for this design. Python ABCs can express similar requirements, but the language mechanisms are not identical.
20 | ABSTRACTION SUPPORTS MODULAR CODE
A module is a unit of a program with a focused responsibility and a clear way for other code to use it. Classes can form useful units, and Python files can group related classes and functions. In a larger app, notification_models.py could contain the base and concrete classes, while a separate page controller calls show_previews.
# In another file, with notification_models.py available:
from notification_models import EmailNotification, ScreenNotification, show_previews
items = [EmailNotification("Maya"), ScreenNotification("Leo")]
show_previews(items, "Science club starts at 16:00")
To try this version, move the relevant definitions from the complete program into notification_models.py and put its demonstration calls under an if __name__ == "__main__": guard. Importing then loads definitions without unexpectedly running the demonstration. The controller relies on the public operations rather than copying channel logic.
21 | CHANGE THE IMPLEMENTATION, KEEP THE CONTRACT
Suppose the school wants screen previews to use capital letters in the channel heading. We can change the string built by ScreenNotification.format_message while keeping its input and return type. preview and show_previews still call the same operations.
The benefit is reduced coupling: callers depend on a stable useful contract rather than exact internal steps. However, not every change is safely hidden. Changing the result from a string to a list, requiring a new argument or adding unexpected sending side effects would break the established expectations.
Abstraction gives us a boundary for change. Tests and documentation help establish which changes stay within that boundary. It does not make every implementation change harmless.
22 | ADD A NEW CHANNEL WITHOUT COPYING THE ALGORITHM
class AppNotification(Notification):
def format_message(self, text):
return "App: " + text
items = [EmailNotification("Maya"), AppNotification("Sam")]
show_previews(items, "Bring your laptop")
The new class supplies the required formatting step. It inherits recipient preparation and preview construction. The common caller works without another branch to recognise AppNotification.
This shows three related benefits: abstraction defines the useful operations, inheritance reuses the known implementation, and polymorphism lets the same caller use the new formatter. Explain how each contributes instead of naming all three as if they were one feature.
23 | ABSTRACT MARKERS DO NOT PROVE CORRECTNESS
class BrokenNotification(Notification):
def format_message(self, text):
return 99
broken = BrokenNotification("Sam")
try:
print(broken.preview("Hello"))
except TypeError:
print("The formatter returned an incompatible value")
Python now permits instantiation because format_message is no longer abstract. However, preview cannot concatenate an integer with its string parts. The example demonstrates that implementing the required name is not enough to satisfy the full contract.
Likewise, Python’s ABC machinery does not generally verify that an overriding method accepts every required argument. Java checks declared method signatures and types, but a method returning a misleading String can still be logically wrong. Both languages need behavioural tests.
24 | TEST THE CONTRACT AND THE SHARED LOGIC
email = EmailNotification(" Maya ")
screen = ScreenNotification("Leo")
assert email.recipient_label() == "To: Maya"
assert email.preview("Hello") == "To: Maya\nEmail: Hello"
assert screen.preview("Hello") == "To: Leo\nScreen: Hello"
assert isinstance(email, Notification)
try:
Notification("Sam")
except TypeError:
print("Abstract construction correctly blocked")
else:
raise AssertionError("Notification should be abstract")
The first test checks shared trimming. The next two check the common preview method combined with two different formatters. The last test checks that the intended abstract-class restriction remains in place. Run these statements after the complete Python definitions.
Also test an unfinished subclass, a new channel and invalid recipients such as whitespace-only text. For a larger application, check relevant edge cases for message content and document whether empty text is allowed. In this example, empty message text is permitted.
25 | LIMITATIONS AND COMMON MISUNDERSTANDINGS
| Claim | Better explanation |
|---|---|
| Abstraction means removing all detail | Expose essential details clearly and leave unnecessary implementation behind the interface |
| An abstract class contains no working code | It can share state, initialization and concrete methods |
| A common interface requires Java interface syntax | Abstract classes can also establish common operations |
| Python pass alone makes a method abstract | Use ABC machinery and @abstractmethod for this instantiation rule |
| A general reference creates a general object | It can refer to a concrete subclass instance |
| Every design needs an abstract class | Use one when a genuine shared contract or partial implementation justifies it |
An unnecessary hierarchy can make a small program harder to follow. A single function may be enough for a task with one simple implementation. Abstract classes become useful when related implementations share meaningful expectations and often some reusable code.
26 | EXPLAIN THE DESIGN WITH CAUSE AND EFFECT
A strong explanation identifies the mechanism and links it to a benefit. For example: Notification declares a common formatting operation, so each concrete channel must supply that part. The preview method reuses that operation through a stable interface; therefore the caller can work with a new channel without duplicating preview construction.
When asked about modular code, explain how responsibilities are separated and how callers depend on the interface. When asked about abstract classes, distinguish declaring a general type from constructing a concrete object. Include an example of required behaviour and shared implementation.
Your challenge is to design an abstract LearningResource with title state, an abstract content_summary() returning a string and a concrete preview() combining them. Implement VideoResource and ArticleResource. Then explain why the base is abstract, which code is reused and how a common caller uses both. The next lesson explores composition and aggregation.