← IB Computer Science

B3.2 · Book pp. 417–452

Fundamentals of OOP for multiple classes

HL only This whole section is for Higher Level students.

Real programs have many classes that depend on each other. This section is about how to connect them well.

What you need to know

  • B3.2.1 Explain and apply inheritance to promote code reuse.
  • B3.2.2 Construct code to model polymorphism, such as method overriding.
  • B3.2.3 Explain abstraction in OOP.
  • B3.2.4 Explain composition and aggregation in class relationships.
  • B3.2.5 Explain commonly used design patterns.
RelationshipMeaningExampleUML
Inheritanceis aA Student is a PersonHollow triangle pointing at the parent
Compositionhas a, and owns its lifeA House has RoomsFilled diamond at the whole
Aggregationhas a, but lives separatelyA Team has PlayersHollow diamond at the whole

Next: inheritance →

B3.2.1 Inheritance

A child class (subclass) derives from a parent class (superclass). It gets the parent’s variables and methods, and only adds what differs. Python writes class Student(Person), and Java writes class Student extends Person.

 

⚠️ Common mistake

Inherit only when “is a” really holds. A Car is not an Engine, even if you want its methods. Deep hierarchies tie classes tightly together, and composition is often better.

✏️ Book corrections

  • The book says a child “takes a copy” of the parent. Nothing is copied. The child shares the parent’s code, so a fix in the parent reaches every child.
  • It says super() must be the first line in Python too. That is a Java rule. Python lets it appear anywhere, but does not call it for you if you override __init__. Java calls a no-argument super() automatically if you leave it out.

Next: polymorphism →

B3.2.2 Polymorphism

Polymorphism means “many forms”: related objects respond to the same call in different ways. The loop in the last program never asks what type each object is. It calls one method, and each object runs its own version.

  • Overriding: a subclass replaces a method, with the same name and parameters.
  • Overloading: one class has several methods of the same name with different parameters. Java has this, but Python does not. The book leaves it out, but it is worth knowing.

🔬 Lab: which version runs?

Bot has move() and name(). SmartBot extends Bot and overrides move(). BossBot extends SmartBot and overrides name().

Overriding built-in methods

PythonUsed byJava
__eq__==equals()
__hash__Use in sets and dictionarieshashCode()
__lt__, __gt__<, >, and sorted()compareTo()
__str__print()toString()
 

Equal objects must have equal hash codes, so override both together.

Next: abstraction →

B3.2.3 Abstract classes

An abstract class cannot be instantiated. It sets a contract: every subclass must provide the abstract methods, so other code can rely on them.

Use one when a method must exist for all subclasses, but no sensible default exists. Every shape has an area, but there is no general formula.

 

The final line fails on purpose.

✏️ Book correction

The book says abstract classes have no executable code and provide no functionality, then later says they have “common code to share”. The second is right. An abstract class can have working methods, like describe() above.

What is an interface?

This is outside the syllabus, but you will see it in Java. An interface lists methods with no instance variables. A class can implement many interfaces, but can extend only one class.

Next: composition and aggregation →

B3.2.4 Composition and aggregation

Both are “has a” relationships. Ask: can the part exist without the whole?

House Room Team Player
Filled diamond: composition. Hollow diamond: aggregation. The diamond is at the whole.
 

🔬 Lab: sort the relationships

The answer depends on the context, so state your reasoning. An engine in a garage can run outside a car.

✏️ Book correction

One of the book’s questions asks why composition is used between Playlist and Track. By its own definition, that is aggregation: a track stays in the library after a playlist is deleted.

Next: design patterns →

B3.2.5 Design patterns

A design pattern is a tested, reusable approach to a common design problem.

PatternIdeaUse
SingletonOnly one object may exist, and it is reachable everywhereSettings, or one database connection
FactoryA method chooses and creates the right class of objectMaking buttons in different styles
ObserverSubscribers are told automatically when something happensButton click listeners, notifications

Singleton

In Java, the constructor is private, and a static getInstance() returns the one object.

 

Factory

 

Observer

 

Next: review →

Quick quiz

1. In Java, a class inherits with…
2. Overriding means a subclass…
3. super is used to…
4. An abstract class…
5. A subclass of an abstract class must, to be instantiated…
6. Which is composition?
7. The aggregation symbol is…
8. Which pattern ensures only one instance?
9. In the observer pattern, the subject…

Exam-style questions

These are written for this site in the style of Paper 2. Answer on paper first, then open the mark points.

  1. Outline why inheritance reduces code duplication. [2]

    Mark points
    • Shared variables and methods are written once in a parent class [1].
    • Each subclass reuses them, adding only what differs [1].
  2. Discuss how polymorphism improves maintainability. [4]

    Mark points
    • Code can call the same method on a parent type [1].
    • Each object runs its own version [1].
    • So new subclasses can be added without changing that code [1].
    • Selection statements on type are avoided [1].
  3. Distinguish between composition and aggregation. [2]

    Mark points
    • In composition, the part cannot exist without the whole, and is destroyed with it [1].
    • In aggregation, the part can exist independently [1].
  4. A Vehicle class has subclasses Car and Bus. Explain why Vehicle might be abstract. [3]

    Mark points
    • No generic vehicle exists to create [1].
    • So instantiation should be prevented [1].
    • Abstract methods make each subclass provide its own version [1].
  5. Construct class Dog, inheriting from Animal(name), that adds breed and overrides speak(). [4]

    Mark points
    • Class header showing inheritance [1].
    • Constructor calls the parent constructor with name [1].
    • Sets breed [1].
    • speak() has the same signature, with a new body [1].
  6. Describe the factory pattern, with an example. [3]

    Mark points
    • Objects are created through a method rather than direct constructors [1].
    • It returns the right subclass, using a parameter [1].
    • For example, a method that returns Circle or Square for a drawing tool [1].
  7. A streaming app has Users, Playlists and Tracks. Identify each relationship, with a reason. [3]

    Mark points
    • User to Playlist can be composition, as the playlists go with the account [1].
    • Playlist to Track is aggregation [1].
    • A track still exists in the library when a playlist is deleted [1].