Learn
B3.1.1 | FUNDAMENTALS OF OOP
01 | ORGANIZE A PROGRAM AROUND THINGS THAT HAVE STATE
A library system needs to know which physical book copy is available and who has borrowed it. The data matters, but so do the actions that change it: borrowing an available copy and returning a borrowed copy.
Object-oriented programming (OOP) organizes a program around objects that combine state with behaviour. A book-copy object can hold its own identifier, title and current borrower, and provide operations for borrowing and returning.
This common SL/HL lesson evaluates classes, objects, encapsulation, inheritance and polymorphism. Their foundations belong here; the later HL multiple-class objectives develop inheritance and related techniques in more detail.
02 | FROM A REAL ENTITY TO A USEFUL MODEL
A physical copy has a cover colour, page count, shelf history, title and many other details. A loan program needs only selected features. OOP models are abstractions shaped by requirements, not complete digital replicas of reality.
Represent a physical copy rather than only a title: two copies of the same title can be borrowed independently. CopyID keeps them distinct. The student is another relevant entity; this first example records the borrower’s ID as text.
Not every object must represent a tangible thing. A report, timer or validation service can also be modeled as an object when that organization is useful.
03 | CLASS AND OBJECT: DEFINITION AND INSTANCE
| Concept | Meaning | Library example |
|---|---|---|
| Class | A definition describing a kind of object and its operations | BookCopy |
| Object / instance | A particular object created using a class | Copy C17 |
| Another instance | A separate object with its own instance state | Copy C18 |
A class is often compared to a blueprint. Creating an instance uses the definition to make a particular object. The two copies can share behaviour while holding different identifiers and borrowers.
A class name is not a list of all its objects. The application still needs appropriate references or collections to find and manage the instances it creates.
04 | ATTRIBUTES DESCRIBE STATE
An attribute is a named member holding information about an object. Instance attributes belong to a particular instance. In our model, copy_id and title identify the copy, while _borrower records its changing loan state.
State means the relevant values at a particular moment. _borrower = None means available; an actual student ID means on loan. This single representation avoids maintaining an available flag that could contradict the borrower field.
The leading underscore follows a Python convention for non-public implementation details. It is not a security barrier or an enforced private access modifier.
05 | METHODS DESCRIBE BEHAVIOUR
A method is an operation defined as part of a class. is_available inspects state; borrow and return_book can change it according to rules. get_borrower retrieves the current borrower without changing the loan state.
A method call specifies a receiver: copy_a.borrow("S01") asks that particular object to perform the borrowing operation. Calling a method on copy_a does not automatically apply it to every BookCopy instance.
Keep the method’s contract clear: inputs, result, state changes and failure behaviour. A printed success message alone is not a well-defined update contract.
06 | A SMALL CLASS WITH ONE RESPONSIBILITY
class BookCopy:
def __init__(self, copy_id, title):
self.copy_id = copy_id
self.title = title
self._borrower = None
def is_available(self):
return self._borrower is None
def get_borrower(self):
return self._borrower
def borrow(self, student_id):
if not isinstance(student_id, str) or not student_id.strip():
raise ValueError("Student ID must be nonempty text")
if not self.is_available():
return False
self._borrower = student_id.strip()
return True
def return_book(self):
if self.is_available():
return False
self._borrower = None
return True
This class manages the loan state of one book copy. borrow returns True after a successful change and False when the copy is already on loan. return_book returns False if there is nothing to return. Invalid student-ID text raises ValueError.
The example assumes valid supplied copy identifiers and titles. A nonempty student ID is not proof that the student exists or is authorized: those application checks are separate.
Read the definition by responsibility rather than memorizing punctuation: initialize state, inspect it, then provide controlled transitions.
07 | INSTANTIATE TWO OBJECTS
class BookCopy:
def __init__(self, copy_id, title):
self.copy_id = copy_id
self.title = title
self._borrower = None
def is_available(self):
return self._borrower is None
def get_borrower(self):
return self._borrower
def borrow(self, student_id):
if not isinstance(student_id, str) or not student_id.strip():
raise ValueError("Student ID must be nonempty text")
if not self.is_available():
return False
self._borrower = student_id.strip()
return True
def return_book(self):
if self.is_available():
return False
self._borrower = None
return True
copy_a = BookCopy("C17", "Networks")
copy_b = BookCopy("C18", "Networks")
print(copy_a.copy_id, copy_b.copy_id)
print(copy_a.is_available(), copy_b.is_available())
The outputs are C17 C18, then True True. Both copies have the same title but different identities and independent instance state.
Calling BookCopy(...) constructs an instance and runs its initialization. __init__ initializes the new instance’s attributes; it does not return the new object as an ordinary result of its own body.
The arguments "C17" and "Networks" supply initial values. The class defines how those values are stored.
08 | SELF MEANS THE CURRENT RECEIVER
In a Python instance method, self refers to the object receiving the call. With copy_a.borrow("S01"), Python supplies copy_a as self and "S01" as student_id.
self._borrower therefore updates copy_a’s borrower. When the same method is called on copy_b, self refers to copy_b instead. This is how one method definition works with many instances.
self is the conventional parameter name, not a special keyword spelling that creates OOP by itself. The important relationship is the bound instance supplied to the method. Java uses this to refer to its current instance.
09 | TRACE ONE OBJECT WITHOUT CHANGING THE OTHER
class BookCopy:
def __init__(self, copy_id, title):
self.copy_id = copy_id
self.title = title
self._borrower = None
def is_available(self):
return self._borrower is None
def get_borrower(self):
return self._borrower
def borrow(self, student_id):
if not isinstance(student_id, str) or not student_id.strip():
raise ValueError("Student ID must be nonempty text")
if not self.is_available():
return False
self._borrower = student_id.strip()
return True
def return_book(self):
if self.is_available():
return False
self._borrower = None
return True
copy_a = BookCopy("C17", "Networks")
copy_b = BookCopy("C18", "Networks")
print(copy_a.borrow("S01"))
print(copy_a.borrow("S02"))
print(copy_a.get_borrower())
print(copy_b.is_available())
| Operation | Result | C17 borrower afterwards | C18 borrower afterwards |
|---|---|---|---|
| Create both | Two objects | None | None |
| C17 borrow S01 | True | S01 | None |
| C17 borrow S02 | False | S01 | None |
| Inspect C17 | S01 | S01 | None |
| Inspect C18 availability | True | S01 | None |
The rejected second borrowing must not replace the first borrower. The unchanged C18 object shows that a shared class definition does not mean shared instance attribute values.
10 | INTERACTIVE: TWO COPIES, SEPARATE STATE
Select a copy and request a borrow or return. The activity models the class above: one copy can be on loan while the other remains available. The state table and history show the receiver, result and resulting borrowers. It does not check a real student database or save loans between visits.
Try borrowing C17 twice with different IDs, then borrow C18. Return C17 and try returning it again. Explain which calls change state, which are rejected and why the other object remains unaffected.
11 | ENCAPSULATION: PUT STATE AND ITS RULES TOGETHER
Encapsulation groups related state and behaviour within a unit such as a class. It supports a clear interface for controlling operations on that state.
The caller requests borrow; it does not need to reproduce the “already on loan” test in every screen. That test is implemented in one place, reducing the risk of inconsistent checks across callers.
An invariant is a property expected to hold for a valid object. Here one copy has at most one current borrower, and the available state corresponds to no borrower. Methods should preserve those rules after valid operations.
12 | INFORMATION HIDING AND ITS LIMITS
Information hiding keeps implementation details behind an interface so other code need not depend on them. A later version could represent loan status differently while keeping borrow and is_available stable for callers.
Python’s _borrower convention signals that callers should not edit it directly, but copy_a._borrower remains technically accessible. Java private can enforce member access restrictions at the language level.
Neither convention nor a private field is a substitute for authorization, input validation, secure storage or concurrency control. They improve program structure and state discipline; they do not make the complete library system secure automatically.
13 | WHY CONTROLLED OPERATIONS MATTER
If callers directly assign borrower values, one screen might replace an existing borrower without checking availability, while another refuses. A controlled borrow operation centralizes the rule.
Avoid exposing every field through unrestricted setters just to claim encapsulation. set_borrower can still bypass the intended borrow/return transitions unless its contract enforces the same rules.
This small object is also not a transaction-safe multi-user database. Two simultaneous borrowing requests require appropriate coordination in the persistence layer; an in-memory method does not by itself solve that larger problem.
14 | INHERITANCE: A MORE SPECIFIC KIND
Inheritance defines a relationship where a subclass derives behaviour or attributes through a superclass. A Book resource and a Laptop resource can specialize a shared Resource abstraction.
Use an “is a” test: a Book is a Resource, so treating it through a suitable Resource interface can make sense. A Library has BookCopy objects; that does not mean a Library is a BookCopy.
Inheritance can reuse common behaviour and provide a shared contract, but it also creates dependencies on the parent design. Choose it when the relationship and substitutability are meaningful, rather than only because two classes happen to share a field name.
15 | POLYMORPHISM: ONE OPERATION, DIFFERENT BEHAVIOUR
class Resource:
def __init__(self, label):
self.label = label
def describe(self):
return f"Resource: {self.label}"
class Book(Resource):
def describe(self):
return f"Read: {self.label}"
class Laptop(Resource):
def describe(self):
return f"Use: {self.label}"
resources = [Book("Networks"), Laptop("Laptop 7")]
for resource in resources:
print(resource.describe())
The outputs are Read: Networks and Use: Laptop 7. The caller uses the same resource.describe() operation, but the method selected depends on the receiving object. This is runtime polymorphic behaviour.
Book and Laptop inherit initialization from Resource and override describe with more specific behaviour. Overriding means replacing an inherited method’s implementation in a subclass while preserving an appropriate contract.
Python can also use objects sharing a compatible method interface without requiring this inheritance relationship. The key benefit is that callers can work through an agreed operation rather than hard-coding a separate type test for every object.
16 | KEEP THE CONTRACT WHEN SPECIALIZING
A caller expects describe to return a description string. A new subclass that returns an unrelated integer or deletes data instead would violate that expectation, even if the method name matches.
Polymorphism is useful when new object types can provide the same required operation without forcing all callers to change. A new resource type may then be added through its implementation of that interface.
This does not guarantee that no code changes anywhere. Construction, configuration, validation or genuinely different requirements may still need updates. Evaluate the actual extension point rather than claiming unlimited flexibility.
17 | COMPOSITION: BUILD WITH COLLABORATING OBJECTS
Composition and object collaboration offer another way to organize responsibilities. A loan service can hold or use book-copy objects and student records, asking them for the information it needs. A Library has resources; a Library does not inherit from every resource type.
A class responsible for one copy should not automatically handle database connections, screen layout, email and every reporting task. Separate responsibilities and connect them through explicit operations.
Composition can avoid rigid inheritance hierarchies, but introduces its own interfaces and coordination work. The best choice follows the model and requirements, not a rule that inheritance or composition must always win.
18 | OOP AND PROCEDURAL PROGRAMMING
| Task | Procedural organization | Object-oriented organization |
|---|---|---|
| One temperature conversion | A function receives a value and returns a result | A class may add little useful structure |
| Many independently loanable copies | Functions operate on record structures passed in | Each object carries state and exposes loan operations |
| Several resource types with shared behaviour contract | Functions may select or dispatch behaviour explicitly | Objects can provide the same method differently |
| A long-lived growing application | Modules and functions can still be well structured | Classes can organize related state, rules and collaboration |
Both approaches can be modular, reusable and testable. OOP is not the only way to write maintainable code, and procedural programming does not mean unstructured spaghetti.
Many practical programs mix functions and classes: use objects for useful stateful models and functions for calculations that do not need an object identity.
19 | ADVANTAGES WHEN THE FIT IS GOOD
For many book copies, a shared class definition avoids duplicating the same operations while retaining independent state. Centralized rules help keep changes consistent across callers.
Encapsulation and information hiding can limit dependencies on representation, so changing internals need not require editing every caller. Polymorphic operations can support new compatible object types.
A clear domain model can make team responsibilities and tests easier to discuss: test borrowing one copy, test duplicate rejection, then test service-level collaboration. These benefits depend on sensible responsibilities and interfaces.
20 | DISADVANTAGES AND DESIGN COSTS
Classes, object relationships and extra abstraction can add setup and navigation costs. For a tiny one-off calculation, a function can express the solution more clearly than a hierarchy.
Poor inheritance design can tightly couple subclasses to parent details. A parent change can affect many dependants, and deep hierarchies can make behaviour harder to locate.
Objects can introduce memory overhead and method-call or indirection costs compared with some simpler representations, depending on the language and runtime. These are reasons to measure important workloads, not proof that every OOP program is slow.
State spread across collaborating mutable objects can make faults hard to reproduce if ownership and update rules are unclear. OOP does not automatically create a good design.
21 | JAVA: PRIVATE STATE AND INSTANCE METHODS
public class BookCopyExample {
static class BookCopy {
private final String copyId;
private String borrower;
BookCopy(String copyId) {
this.copyId = copyId;
this.borrower = null;
}
public boolean isAvailable() {
return borrower == null;
}
public boolean borrow(String studentId) {
if (studentId == null || studentId.trim().isEmpty()) {
throw new IllegalArgumentException("Student ID required");
}
if (!isAvailable()) {
return false;
}
borrower = studentId.trim();
return true;
}
public String getCopyId() {
return copyId;
}
}
public static void main(String[] args) {
BookCopy first = new BookCopy("C17");
BookCopy second = new BookCopy("C18");
System.out.println(first.borrow("S01"));
System.out.println(first.borrow("S02"));
System.out.println(second.isAvailable());
}
}
The outputs are true, false and true. private restricts access to the fields; callers use instance methods. this refers to the current object, and final prevents reassignment of copyId after initialization.
The enclosing example contains a nested class for a complete single-file demonstration. The nested declaration’s static keyword does not make borrower shared: borrower is still an instance field. Static versus instance members are examined directly in B3.1.3.
22 | TEST THE OBJECT’S CONTRACT
class BookCopy:
def __init__(self, copy_id, title):
self.copy_id = copy_id
self.title = title
self._borrower = None
def is_available(self):
return self._borrower is None
def get_borrower(self):
return self._borrower
def borrow(self, student_id):
if not isinstance(student_id, str) or not student_id.strip():
raise ValueError("Student ID must be nonempty text")
if not self.is_available():
return False
self._borrower = student_id.strip()
return True
def return_book(self):
if self.is_available():
return False
self._borrower = None
return True
copy_a = BookCopy("C17", "Networks")
copy_b = BookCopy("C18", "Networks")
assert copy_a.is_available()
assert copy_a.borrow("S01") is True
assert copy_a.borrow("S02") is False
assert copy_a.get_borrower() == "S01"
assert copy_b.is_available()
assert copy_a.return_book() is True
assert copy_a.return_book() is False
assert copy_a.is_available()
These checks cover initialization, a valid transition, rejected borrowing without damage, independence of another instance and repeated returns. No output means the assertions passed in a normal run with assertions enabled.
Also test blank or non-text student IDs for the promised ValueError and unchanged borrower state. Integration tests still need to check the surrounding service, stored records and user interface.
23 | EVALUATE A LIBRARY OR EQUIPMENT SYSTEM
A school lends hundreds of distinguishable books and devices, each with a changing availability state. Multiple screens need the same borrowing rules. A useful OOP model can represent instances and centralize their valid transitions.
Different resource types may share operations while specializing some behaviour, giving a reason to consider an interface or carefully designed inheritance. A coordinating service can handle persistence and cross-object policies.
The benefit is reduced duplication and clearer responsibility. The costs are more design work, relationships and testing. A justified conclusion is that OOP suits these stateful requirements, provided the design avoids one enormous all-purpose class and handles storage/concurrency separately.
24 | EVALUATE A SMALL DATA-TRANSFORMATION SCRIPT
A one-off program reads a text file, converts temperatures and writes a report. If it has no useful independent entity state or type-specific behaviour, a few functions and a file-processing loop may be enough.
Creating a TemperatureManagerFactory hierarchy could add names and dependencies without improving the task. Procedural modularity can already separate conversion, reading and reporting.
If the requirements grow to simulate many devices with individual state and different behaviours, the balance may change. Evaluate the current and credible future requirements rather than inventing complexity to justify a paradigm.
25 | COMMON CONFUSIONS TO REPAIR
| Confusion | Clearer distinction |
|---|---|
| Class and object are the same | Class defines a kind; an instance is a particular object |
| Two same-title copies are the same object | Identifiers and independent state distinguish physical copies |
| self is the whole collection | self refers to the receiving instance |
| A method call updates every instance | Only the state actually accessed or mutated is changed |
| Encapsulation means every field has a setter | Controlled operations should preserve the required rules |
| Python underscore enforces private access | It signals a convention, not an access barrier |
| Inheritance means any has-a relationship | Use meaningful is-a specialization; collaboration can model has-a |
| Polymorphism means every method behaves identically | The same compatible operation can have type-specific implementation |
| OOP automatically makes code secure or fast | Security and performance depend on the whole system and implementation |
26 | WRITE A BALANCED EVALUATION
An Evaluate response should weigh strengths and limitations in context and reach a supported judgement. Begin with the scenario’s state, operations, variations and scale, then connect OOP features to those needs.
For example: “Each copy retains its own borrower, therefore one class can provide shared loan rules without merging the copies’ states. However, storage and concurrent requests still require separate design, so the class is a useful model rather than a complete lending system.”
Avoid an unsupported claim that OOP is always better. Explain what the design helps, what it costs, and when a simpler function-based organization would be adequate.