IB COMPUTER SCIENCE | B3

OBJECT-ORIENTED PROGRAMMING REVISION

Connect class design, object state, access rules and HL class relationships. Reconstruct worked examples, filter SL/HL material and build your revision list.

Selections are retained, including cards hidden by filters. All selected cards remain in your revision list.

YOUR B3 REVISION ROUTE

B3 covers the fundamentals of object-oriented programming, class design, shared and instance members, object creation and encapsulation. B3.2 adds deeper inheritance, polymorphism, abstraction, composition, aggregation and design patterns for HL. The basic ideas named in B3.1.1 remain part of common SL/HL revision even when the detailed B3.2 work is hidden.

Use Revise to reconstruct examples and explain choices. Use Flashcards to test recall, filter by subsection or objective, and select the ideas you need to revisit. There are 180 cards: 90 common SL/HL and 90 HL-only.

Filters do not erase selected cards. Your revision list includes selections hidden by a filter and can be copied. Selections last while this page remains open.

B3.1.1 | CLASSES, OBJECTS, STATE AND BEHAVIOUR

A class defines a kind of object: its attributes represent state, and its methods provide behaviour. An object is a particular instance. Two library copies can use the same class but hold different copy identifiers and borrowing states.

A method call can return information, change state or both, according to its contract. Trace the specific receiving object before deciding which attributes change. Do not assume changing one instance updates every instance.

Encapsulation groups state and behaviour with appropriate access boundaries. Inheritance specialises a general class, while polymorphism lets a common operation use different implementations. Evaluate these ideas against a real requirement rather than simply listing their names.

WORKED | TWO OBJECTS AND AN ALIAS

class Counter:
    def __init__(self):
        self.value = 0

    def increment(self):
        self.value += 1

a = Counter()
b = Counter()
alias = a
alias.increment()
print(a.value, b.value)
print(alias is a)
# 1 0
# True

There are two Counter instances and three variable names. alias and a refer to the same object; b refers to another. The method called through alias updates a.value, because both routes reach the same instance. Assignment of a reference does not clone the object.

In Java, == on object references checks identity. For object value comparison, use an appropriate equals implementation. Equality and identity are different questions.

EVALUATE | WHEN OOP FITS THE PROBLEM

OOP is useful when a system contains related entities with state and operations, such as library copies, members and loans. A focused class can keep relevant rules close to the data, while compatible interfaces support reuse and extension.

The costs include additional abstractions, relationships and sometimes indirection. A small one-off calculation may be clearer as a function. A large inheritance hierarchy can make dependencies harder to follow if the specialisations do not preserve sensible contracts.

A balanced answer links a feature to an effect in the scenario: encapsulated borrowing rules can reduce invalid state changes, therefore different interfaces can reuse the same checks. Then identify a relevant cost rather than claiming OOP is always superior.

B3.1.2 | DESIGN FROM REQUIREMENTS

Start by identifying what one object represents. Separate attributes that must be remembered from inputs that only one call needs. Give each method a clear purpose, inputs, returned result and state-change policy.

For a BookCopy, copy_id identifies an individual copy, title describes it and borrower_id can represent the current borrower. borrow(member_id) should reject a second active loan; return_book() should restore availability. A name such as process_everything hides responsibilities.

Do not duplicate authoritative state unnecessarily. A historical Loan object and a current-only borrower field are different models; if both are stored, specify how consistency is maintained. Choose the model from the requirements before drawing classes.

WORKED | READ A UML CLASS

BookCopy

− copy_id: String

− borrower_id: String [0..1]

+ borrow(member_id: String): Boolean

+ return_book(): Boolean

+ is_available(): Boolean

Three compartments: class name, attributes and operations. Visibility is illustrative; language access rules still matter.

The + symbol means public and − means private. # commonly denotes protected and ~ package visibility in UML. Underlining denotes class/static features; italics can denote abstract classes or operations. Do not confuse a return type with a parameter type.

A multiplicity near one end describes how many objects at that end can relate to one object at the other. For historical loans, a copy can have many Loan records over time while a separate constraint allows at most one active loan.

B3.1.3 | STATIC AND INSTANCE MEMBERS

Member Where its state belongs Typical use
Instance attribute Each individual object A student’s name or score
Class/static attribute Shared at the class level A count or shared category setting
Instance method Uses a receiving object Add points to this student
Static method No automatic receiving instance A utility operation not needing instance state

In Java, static is explicit. An instance method can use its receiving object’s fields; a static method needs an object reference to access an instance field. A static method is not merely a method called from main.

In Python, instance attributes are commonly assigned to self in __init__. @staticmethod supplies no automatic self or cls. @classmethod is a different mechanism: it receives the class as cls. Distinguish these rather than describing every class-level operation as identical.

WORKED | SHARED STATE AND SHADOWING

class Student:
    school = "Aiglon"

    def __init__(self, name):
        self.name = name

a = Student("Maya")
b = Student("Leo")
a.school = "Local label"
Student.school = "Updated school"
print(a.school)
print(b.school)
# Local label
# Updated school

Assigning a.school creates an instance attribute that shadows the class attribute for that instance. b has no such instance attribute and still finds Student.school. Changing the class value does not overwrite a’s shadow.

A mutable class list can accidentally be shared by every instance. If each object needs its own list, create it inside __init__. A class counter update should deliberately update the class attribute instead of accidentally creating an instance shadow.

B3.1.4 | CONSTRUCT CLASSES AND INSTANTIATE OBJECTS

A class definition establishes the operations and state arrangement; an instantiation expression creates an object. In Python, __new__ allocates or returns an instance and __init__ prepares it. __init__ should not return the new object.

In Java, a constructor uses the class name and has no return type. It initializes a new instance, often validating inputs and setting defaults. Constructor overloading can support different permitted argument lists.

Keep construction and references separate. Rebinding a variable to a new object changes where that variable points; it does not make every other alias point to the new object. A domain identifier is data, while runtime object identity is a separate concept.

WORKED | REBINDING AND DEFAULT STATE

class Device:
    def __init__(self, device_id, battery=100):
        self.device_id = device_id
        self.battery = battery

robot = Device("R01")
alias = robot
robot = Device("R02", 60)
alias.battery -= 10
print(alias.device_id, alias.battery)
print(robot.device_id, robot.battery)
# R01 90
# R02 60

The original R01 remains reachable through alias. robot now refers to a separate R02 instance. Updating the original does not change the second object.

Construction should establish the intended valid state. The compact example assumes sensible inputs to isolate reference behaviour; the encapsulation example below adds explicit battery validation.

B3.1.5 | ENCAPSULATION AND INFORMATION HIDING

Encapsulation brings state and relevant behaviour together. Information hiding keeps implementation decisions behind a useful interface. A method such as use_power(amount) can enforce a rule that a general battery setter would leave every caller to implement.

A rejected operation should preserve the relevant state unless the contract says otherwise. Private access is not a complete security boundary against every form of tampering, and a public setter that accepts arbitrary values does not protect an invariant just because the field itself is private.

In Python, _battery signals internal use by convention. __battery triggers name mangling, not Java-style absolute privacy. A property can expose controlled read access or validation, but deliberate access to Python internals remains possible.

WORKED | CONTROLLED UPDATES PRESERVE AN INVARIANT

class Battery:
    def __init__(self, level=100):
        if type(level) is not int or not 0 <= level <= 100:
            raise ValueError("Level must be an integer from 0 to 100")
        self._level = level

    @property
    def level(self):
        return self._level

    def use_power(self, amount):
        if type(amount) is not int or amount < 0 or amount > self._level:
            return False
        self._level -= amount
        return True

battery = Battery(15)
print(battery.use_power(10), battery.level)
print(battery.use_power(10), battery.level)
# True 5
# False 5

The invariant is a whole-number charge from 0 to 100. The second request is rejected without changing the remaining 5. No general-purpose setter is needed for the public interface.

A getter returning a mutable internal list can still expose state. Return an appropriate copy or immutable value view when callers should inspect rather than edit. A shallow copy protects the container structure, not all mutable objects inside it.

B3.2.1 | INHERITANCE, EXTENSION AND REUSE HL ONLY

Inheritance models an is-a specialisation. A Robot is a kind of Device. The subclass can inherit suitable operations and extend the model with new state or behaviour. It should remain usable where the relevant Device contract is expected.

A subclass instance has its base-defined state and added state in one object. super does not create a separate superclass object. In Python, a subclass can inherit __init__ if it defines none; if it defines a new initializer, it should explicitly perform any necessary base initialization. Java constructors are not inherited.

Reuse has a cost: subclass behaviour depends on its base class. Choose inheritance for a meaningful specialisation; use component relationships for has-a collaboration.

WORKED | INITIALIZE THE BASE, THEN EXTEND HL ONLY

class Device:
    def __init__(self, device_id):
        self.device_id = device_id

    def report(self):
        return "Device " + self.device_id

class Robot(Device):
    def __init__(self, device_id):
        super().__init__(device_id)
        self.scans = 0

    def scan(self):
        self.scans += 1

robot = Robot("R01")
robot.scan()
print(robot.report(), robot.scans)
# Device R01 1

The robot reuses report and the identifier initialization. It adds scans and scan. Python super follows the method resolution order; in this single-inheritance example, the initializer used is Device.__init__.

Java public members are generally accessible through permitted references. Protected supports same-package access and qualified subclass access across packages, with receiver restrictions. Package-private access is limited to the package. Private base state is managed by base operations, rather than directly accessed as an inherited subclass member; Java’s nested-class access rules add a separate nuance.

B3.2.2 | OVERRIDING AND DYNAMIC DISPATCH HL ONLY

A subclass overrides an inherited instance operation with a compatible implementation. The common caller can use the same operation while the actual object determines which implementation runs.

In Java, Device item = new Robot(...) gives the variable a declared Device type while its object remains a Robot. A normal overridden instance report call uses the Robot implementation at runtime. The declared type still controls which operations are available to the caller at compile time.

Preserve the contract: accepted arguments, expected results and important side effects. Python can replace an abstract or inherited name with a method whose required parameters do not fit old calls; tests must catch that incompatibility.

WORKED | ONE LOOP, DIFFERENT IMPLEMENTATIONS HL ONLY

class Device:
    def report(self):
        return "Device ready"

class Robot(Device):
    def report(self):
        return "Robot scan ready"

class Sensor(Device):
    pass

for item in [Robot(), Sensor()]:
    print(item.report())
# Robot scan ready
# Device ready

The Robot override runs first. Sensor has no override, so the inherited Device method runs. Sensor remains a Sensor object; the wording of its returned string does not change its class.

A reusable caller depends on a meaningful compatible operation. In Python, duck typing can also accept an unrelated class with a suitable report method, without requiring that it inherits Device.

DISTINGUISH | JAVA OVERLOADING AND OVERRIDING HL ONLY

Question Overloading Overriding
What changes? Parameter lists for the same method name Subclass implementation of an inherited instance operation
Selection in the shown Java model Compiler chooses an applicable signature Runtime chooses implementation from the actual object
Return type alone enough? No Return must be compatible with inherited declaration
Meaning of static polymorphism Compile-time signature selection Not the ordinary dynamic override mechanism

If reporter.show(Device) and reporter.show(Robot) are overloads, a Device variable holding a Robot selects show(Device). Inside that method, an overridden report call can still run Robot.report. Signature selection and instance dispatch are two distinct steps.

Static polymorphism does not require Java static methods. Java class methods are hidden rather than dynamically overridden. Python does not implement Java-style overload sets by repeating def; use one suitable implementation or an appropriate dispatch mechanism. Compile-time choice alone does not prove an entire program is faster.

B3.2.3 | ABSTRACTION AND ABSTRACT CLASSES HL ONLY

Abstraction presents essential operations and expectations while leaving unnecessary implementation details out of the caller’s view. The interface should be precise about what a caller supplies and receives.

An abstract class can establish common operations, store shared state and provide concrete methods. It cannot be directly instantiated. A concrete subclass must satisfy the remaining abstract requirements, but the language’s abstract checks do not prove every behavioural promise.

Abstract declared types can still be used for variables and collections referring to concrete subclass instances. The general design meaning of interface is broader than Java’s interface keyword.

WORKED | A SHARED ALGORITHM CALLS A REQUIRED STEP HL ONLY

from abc import ABC, abstractmethod

class Notification(ABC):
    @abstractmethod
    def format_message(self, text):
        pass

    def preview(self, text):
        return "Preview | " + self.format_message(text)

class EmailNotification(Notification):
    def format_message(self, text):
        return "Email: " + text

print(EmailNotification().preview("Hello"))
# Preview | Email: Hello

Notification.preview is working shared code. It calls the EmailNotification formatter on the same concrete object. Direct Notification() construction raises TypeError; an unfinished subclass remains abstract. Python ABC machinery does not generally validate the full signature or returned meaning of an override.

Java abstract method declarations have no body and end with a semicolon. A non-abstract class missing an implementation fails compilation. Java interfaces can also contain certain implemented methods, so avoid the blanket claim that interfaces contain no code.

B3.2.4 | COMPOSITION AND AGGREGATION HL ONLY

Feature Composition Aggregation
Whole–part rule Exclusive ownership; dependent modelled lifetime Grouping of independently existing parts
Example Report and its owned sections Club and independent students
When the whole is removed Owned parts cease as active content under the model’s rules Independent students remain usable
UML marker at the whole Filled diamond Hollow diamond

The class names alone do not establish the relationship. Ask who owns the part, whether it can be shared and what removing the whole means in this scenario. A component object inside another object can support either model depending on those rules.

A report can create sections internally and expose title snapshots rather than mutable section objects. A club can receive existing Student references. A shallow copy of a membership list separates the list structure but keeps the student references shared.

WORKED | SHARING AND DOMAIN LIFETIME HL ONLY

Action Report / composed section Student / aggregated membership
Create whole Report can create its owned parts Club receives existing students
Share part between two wholes Not permitted for the same owned part at the same time The same student can join two clubs in this model
Remove whole in the application Remove or deactivate dependent sections Remove membership; keep student
Delete a Python name May leave object reachable through an alias Likewise does not automatically delete a student

del club removes a name, not every reference to the object. A designed disband operation changes application state. Garbage collection and domain deletion are different concerns; neither Python nor Java promises that whole–part diagrams instantly erase bytes.

Delegation means asking a component to do part of a task. A controller can ask a motor to set its speed. That call alone does not establish the motor’s lifetime ownership.

B3.2.5 | SINGLETON, FACTORY AND OBSERVER HL ONLY

Pattern Mechanism Benefit and caution
Singleton Control normal construction/access to a shared instance in scope Consistent shared access; mutable global dependencies can complicate testing
Factory Supply a suitable product behind a creation operation Centralise creation; the factory still depends on available concrete products
Observer Maintain subscribers and invoke a common update operation after a change Extend reactions; specify unsubscribe, timing and failure policy

A simple factory selection function is not automatically the specialised Factory Method pattern, which uses overridable creation operations on creator subclasses. Observer does not automatically create background threads or reliable network messaging.

A singleton is not one universal object across every web-server process. Passing one ordinary instance to callers can be a clearer alternative when shared identity is needed without enforced global access.

WORKED | TRACE OBSERVER NOTIFICATIONS HL ONLY

Action Current subscribers Display records History records
Subscribe display and history Display, History None None
Set score to 3 Display, History 3 3
Unsubscribe history Display 3 3
Set score to 5 Display 3, 5 3
Set score to 5 again, unchanged notifications suppressed Display 3, 5 3
Reject invalid negative score before mutation Display 3, 5 3

Subscription need not send an initial value unless the policy says it does. In the lesson implementation, callbacks run synchronously and the subscriber list is snapshotted for each dispatch. An observer exception can propagate after the subject state has changed.

Observers can remain reachable while subscribed, so clean up registrations when screens close. An observer that triggers another score change can cause nested notifications; make the re-entrancy policy explicit.

COMMON MISTAKES | COMMON SL/HL MATERIAL

Mistake Correction
A class and an object are the same A class defines a type; an object is a particular instance
Assignment clones an object Aliases can reach the same object
Every attribute should be class-level Keep per-object state on instances
A private field with any setter is protected Validate operations and preserve invariants
Python underscore provides absolute privacy It signals an access convention
UML alone guarantees correct behaviour Contracts need implementation and tests

COMMON MISTAKES | HL EXTENSIONS HL ONLY

Mistake Correction
super creates another object It selects a suitable inherited implementation for the same object
Declared Java type chooses every override Actual runtime type selects ordinary overridden instance behaviour
Return type alone creates an overload Overloads need different parameter lists
An abstract class has no working methods It can contain shared concrete implementation
Composition and inheritance are identical Whole–part ownership differs from is-a specialisation
Deleting a name deletes all parts Follow domain ownership and actual references
Observer always means asynchronous Timing depends on implementation
Singleton always crosses processes Its instance rule has a runtime scope

PUT THE IDEAS TOGETHER

Model a library system with separate BookCopy instances and controlled borrow/return operations. Design UML before coding, establish valid initial state, choose instance fields for copy-specific data and test independent objects plus aliases. These are common B3.1 tasks.

For a written answer, link cause and effect: controlled borrowing operations reject a second loan, so callers cannot accidentally bypass the rule through the intended interface, therefore interfaces can reuse consistent behaviour. Avoid unsupported promises of complete security.

Use the selected flashcards as a focused plan, then attempt the separate end-of-topic review to practise applying the concepts and communicating answers.

INTEGRATED HL SCENARIO | A RESOURCE PORTAL HL ONLY

A Resource abstraction defines preview(), and concrete Article and Video classes implement the variable behaviour. A factory supplies a suitable resource from a selected type. The page can call preview through the common interface, so new compatible resource types need fewer caller changes.

A StudyGroup can aggregate independently existing Student objects. A Draft can composition-own its paragraph objects if their active lifetime belongs to that draft. An observer can refresh a dashboard after a publication state change.

Do not force every pattern into the project: justify each from an actual requirement. Test shared contracts, access rules, state changes, aliases and lifecycle policies. Compare the benefit with the extra dependencies introduced.