A Level Computer Science · Chapter 22 · Component 02: Algorithms and programming
Object-oriented programming models a problem as objects that bundle data with the methods allowed to change it, organised into classes that can inherit from one another.
This chapter teaches how to define classes, create objects and call their methods. You will protect data with encapsulation, reuse code with inheritance, and let one method call behave differently for different objects through polymorphism.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- define a class with attributes, methods and a constructor, and create objects from it
- explain encapsulation, and write private attributes with getter and setter methods
- create a subclass that inherits from a parent class, and call the parent's constructor
- override a method, and predict which version runs for an object
- explain polymorphism, and use it to treat different objects through one interface
- explain that variables hold references to objects, and the difference between inheritance and aggregation
- compare object-oriented and procedural programming, and draw and read class diagrams
Time: three sessions, about 4 hours, plus the programming task.
You need first: functions, procedures and parameters from Subroutines and recursion, and records from Arrays, records, stacks and queues.
The big picture
The big picture
A bank has millions of accounts. Each one has its own balance and its own owner, but every account can be paid into and drawn from in the same way. It would be strange to write a separate deposit routine for every account. It makes more sense to describe what an account is once, then create as many as are needed.
That description is a class. A class lists the data each account holds, called its attributes, and the actions it can carry out, called its methods. Each actual account is an object, an instance of the class, with its own values for the attributes.
The balance should not be changed by just any part of the program. A withdrawal should be refused if there is not enough money. So the balance is kept private, and the only way to change it is through the deposit and withdraw methods, which check every request. Keeping data behind methods in this way is encapsulation.
Some accounts are special. A savings account is an account that also earns interest. Rather than writing it from scratch, it can inherit everything from Account and add only what is new. This is inheritance, and it lets programs reuse tested code.
A current account and a savings account might both have a method called monthEnd, but each does something different. A program can call monthEnd on every account in a list without knowing which kind each one is, and the right version runs every time. This is polymorphism.
Object-oriented programming, or OOP, is used to build most large modern systems, from games to banking software. Its ideas, classes, objects, encapsulation, inheritance and polymorphism, make large programs easier to build in teams, test in pieces and change safely.
The key shift is in how a program is described. A procedural program says what steps to carry out on which data. An object-oriented program describes the things in the problem, what each one knows, and what each one can do. The steps then come from objects asking one another to act.
Most of the code in this chapter is written in exam pseudocode and in Python. The ideas carry over directly to Java, C# and other object-oriented languages, where the words change a little but the structure is the same. Learning to read a class in one language makes it easy to read in another.
Section 1
Classes and objects
Classes, attributes and methods
A class is a blueprint that defines what a kind of object holds and can do. Its attributes are the variables each object has, such as owner and balance. Its methods are the subroutines each object can run, such as deposit. A class on its own holds no data; it describes the data its objects will hold.
An object is one instance of a class, created at run time with its own copy of every attribute. Creating an object is called instantiation. Two Account objects share the same methods, but each has its own balance, so paying into one leaves the other unchanged.
Common mistake: confusing a class with an object. A class is the description, like the plan for a house. An object is one thing built from it, like one actual house. A program has one Account class but can create thousands of Account objects, each with its own data.
Identifying classes in a problem
A useful first step in designing an object-oriented program is to read the description of the problem and pick out the nouns. In "a library lends books to members", the nouns library, book and member are candidate classes. The verbs, such as lends, suggest methods.
The details each thing must remember become its attributes. A book needs a title, an author and whether it is on loan. A member needs a name and a list of borrowed books. Choosing attributes carefully matters, because every object of the class will carry them.
Not every noun becomes a class. Some are just attributes of another class, such as a book's title. Others are outside the system altogether. Deciding which is which is part of the design, and it usually takes a few attempts.
Constructors
A constructor is a special method that runs when an object is created. It sets up the object's attributes with their starting values. In exam pseudocode it is called new, and in Python it is init. The constructor's parameters let each object start with different data.
class Account
private owner
private balance
public procedure new(givenOwner)
owner = givenOwner
balance = 0
endprocedure
public procedure deposit(amount)
if amount > 0 then
balance = balance + amount
endif
endprocedure
public function getBalance()
return balance
endfunction
endclass
myAccount = new Account("Asha")
myAccount.deposit(5000)
Methods are called with dot notation: myAccount.deposit(5000) runs the deposit method on the object myAccount. Inside the method, balance means that object's own balance. Balances in this chapter are stored in pence, as integers, so that every total is exact.
Static attributes
Most attributes belong to each object, but sometimes a value belongs to the class as a whole. A count of how many accounts have been opened is the same for every account, so it is stored once, as a class attribute, often called a static attribute. The constructor can add 1 to it each time an object is made.
Class attributes are shared, so a change made through one object is seen by every object. That is useful for counters and constants, but it brings back the risks of global variables if it is overused.
Worked example 1: two objects from one class
Two accounts are created: a for Asha and b for Ben. Asha deposits 5000 and then 1500; Ben deposits 2000. Give each balance.
| Working | Reason |
|---|---|
| a = new Account("Asha") and b = new Account("Ben") both start at 0 | The constructor sets each new balance to 0 |
| a.deposit(5000) then a.deposit(1500) give a's balance 6500 | Both calls change a's own balance |
| b.deposit(2000) gives b's balance 2000 | b has its own separate balance |
| a holds 6500 pence and b holds 2000 pence | Each object keeps its own attributes |
Worked example 2: a sequence of method calls
An account opens with 0. The calls deposit(5000), withdraw(2000) and deposit(750) are made. The withdraw method takes money only if the balance stays at 0 or above. Give the balance after each call.
| Working | Reason |
|---|---|
| deposit(5000) makes the balance 5000 | A positive deposit is added |
| withdraw(2000) leaves 3000, which is allowed | The balance stays above 0 |
| deposit(750) makes the balance 3750 | The deposit is added to the current balance |
| Final balance: 3750 pence, or £37.50 | Every change went through a method |
The object's own reference
Inside a method, the object needs a way to refer to itself, so that it can reach its own attributes. In Python, that is the first parameter of every method, called self by convention. Writing self.balance means "this object's balance", which is why two accounts never mix up their balances.
Python passes self automatically. The call myAccount.deposit(5000) runs deposit with self set to myAccount and amount set to 5000. Other languages, such as Java and C#, use the keyword this for the same idea, and leave it out when there is no confusion.
Class diagrams
A class diagram draws a class as a box in three parts: its name, its attributes and its methods. A minus sign before a member marks it private, and a plus sign marks it public. Types can be added after a colon, such as balance : Integer.
Class diagrams let a team agree on a design before any code is written. Each programmer can see what every class holds and what it offers to the others. The diagram is then a contract: as long as each class provides the methods shown, the pieces fit together.
Objects in memory
Each object occupies its own block of memory, holding its attribute values. The class's methods are stored once, separately, and every object uses the same code. When a method runs, it is given the object it was called on, so it works on that object's block of memory and no other.
Check yourself. A class Dog is used to create rex and fido. How many classes and how many objects are there, and does changing rex's name change fido's?
Show the answer
There is one class, Dog, and two objects, rex and fido. Each object has its own name attribute, so changing rex's name has no effect on fido's.
Section 2
Encapsulation
Hiding data behind methods
Encapsulation means bundling an object's data together with the methods that act on it, and hiding the data from the rest of the program. Attributes are made private, so only the object's own methods can read or change them. The methods that other code may call are made public.
Private data protects an object from misuse. The balance of an Account can only change through deposit and withdraw, so the checks inside those methods can never be skipped. If the rules change, only the class needs editing, because no other code touches the balance directly.
Common mistake: making attributes public so other code can change them. A public balance could be set to any value by any part of the program, skipping every check. A negative deposit or an overdrawn withdrawal would go through. Keep attributes private and change them only through methods.
Encapsulation is also called information hiding. Other code knows what an object can do, through its public methods, but not how it does it. The class could change how it stores the balance, and no other code would notice. All that matters is that getBalance still returns the right amount.
That separation between what and how is the same idea as abstraction. A driver uses a steering wheel and pedals without knowing how the engine works. A programmer uses an object's public methods without knowing how its data is stored. Either side can be improved without breaking the other.
Getters and setters
A getter is a public method that returns the value of a private attribute, such as getBalance(). A setter is a public method that changes a private attribute, checking the new value first. A class can offer a getter without a setter, so that an attribute can be read but never changed from outside.
Figure 22.1 steps through calls on an encapsulated account. Watch which calls the methods refuse. Then switch on the wrong model, where the balance is public and changed with no checks.
Encapsulation in a bank account
- Balance
- £30.00
- Calls refused
- 1
Validation inside the class
Putting validation inside the class means it is written once and applied everywhere. Without encapsulation, every part of the program that changed a balance would need its own copy of the checks. One forgotten copy would be enough to let bad data in.
A method that refuses a request should tell its caller. It might return False, as the methods in the programming task do, or raise an exception that the caller must handle. Silently ignoring a bad request makes errors hard to spot.
Worked example 3: methods that refuse bad requests
An account opens with 0. The calls deposit(5000), withdraw(2000), withdraw(4000) and deposit(−100) are made. Give the final balance and the calls refused.
| Working | Reason |
|---|---|
| deposit(5000) then withdraw(2000) leave 3000 | Both requests pass their checks |
| withdraw(4000) is refused, so the balance stays 3000 | It would take the balance below 0 |
| deposit(−100) is refused, so the balance stays 3000 | A deposit must be positive |
| Final balance 3000, with calls 3 and 4 refused | The methods protect the balance |
If the balance were public and changed directly, the same four changes would give 5000 − 2000 − 4000 − 100 = −1100. Encapsulation is what stops that.
Worked example 4: an overdraft limit
A setter fixes an overdraft limit of 1000, so the balance may go as low as −1000. The account holds 3000. Is withdraw(4000) allowed, and what is the balance afterwards?
| Working | Reason |
|---|---|
| The new balance would be 3000 − 4000 = −1000 | Work out the result before allowing it |
| The limit allows any balance of −1000 or more | The overdraft limit is 1000 |
| −1000 is not below the limit, so the withdrawal is allowed | The check uses greater than or equal |
| The balance is now −1000 | The rule lives inside the method |
Public, private and protected
Most languages offer more than two levels of access. A public member can be used by any code. A private member can be used only inside its own class. A protected member can be used inside its class and its subclasses, which lets a child class reach data that is still hidden from everyone else.
Python does not enforce privacy strictly. A name starting with two underscores is hidden by changing its name behind the scenes, and a single underscore is a polite signal that a member is private. Exam pseudocode uses the keywords public and private explicitly.
Methods can be private too. A class might have a private helper method, such as checkAmount, used by both deposit and withdraw. Keeping it private means other code cannot call it out of context, and it can be changed freely as long as the public methods still work.
Check yourself. Why might a class provide getBalance() but no setBalance()?
Show the answer
Other code needs to read the balance, so a getter is provided. But the balance should only change through deposits and withdrawals, which check each request, so there is no setter that would let it be set directly.
Section 3
Inheritance
Subclasses
Inheritance lets a new class, the subclass or child class, take on all the attributes and methods of an existing class, the superclass or parent class. The subclass then adds its own attributes and methods. A SavingsAccount inherits deposit, withdraw and getBalance from Account, and adds an interest rate and an addInterest method.
Inheritance describes an "is a" relationship: a savings account is an account. Every SavingsAccount object can be used wherever an Account is expected. Code written and tested for Account is reused without being copied, so a fix to Account fixes every subclass as well.
Common mistake: thinking a subclass cannot use its parent's methods. A subclass inherits every public method of its parent. A SavingsAccount object can call deposit even though SavingsAccount does not define it, because the method is found in Account.
Inheritance hierarchies
Inheritance can go several levels deep. A Puppy is a Dog, which is an Animal, so a Puppy object has everything Animal defines, everything Dog adds, and everything Puppy adds. The classes form a hierarchy, drawn with the most general class at the top.
Deep hierarchies are hard to follow, because the behaviour of one object is spread over several classes. Good designs keep hierarchies shallow and put shared behaviour in the class where it truly belongs. A method that only some subclasses need should not be pushed up into the parent.
A subclass can add attributes and methods, and it can override methods, but it should never remove what its parent promises. Code written for an Account must still work when given a SavingsAccount. Keeping that promise is what makes inheritance safe to use.
Calling the parent's constructor
A subclass's constructor usually calls the parent's constructor first, to set up the inherited attributes, then sets up its own. In exam pseudocode this is super.new(...), and in Python it is super().init(...). Forgetting it leaves the inherited attributes without starting values.
class SavingsAccount inherits Account
private rate
public procedure new(givenOwner, givenRate)
super.new(givenOwner)
rate = givenRate
endprocedure
public procedure addInterest()
deposit(balance * rate DIV 100)
endprocedure
endclass
A subclass can be used anywhere its parent is expected. A function written to print an Account's details works on a SavingsAccount too, because a savings account has every method an account has. This substitution is what lets a single list hold accounts of several kinds.
Worked example 5: a subclass at work
A SavingsAccount with a rate of 5% receives deposit(10000), then addInterest() twice. Interest is rounded down to whole pence. Give the balance after each step.
| Working | Reason |
|---|---|
| deposit(10000) makes the balance 10000 | deposit is inherited from Account |
| First addInterest adds 5% of 10000, which is 500, giving 10500 | The subclass's own method uses the rate |
| Second addInterest adds 5% of 10500, which is 525, giving 11025 | Interest is worked out on the new balance |
| Final balance 11025 pence, or £110.25 | Interest compounds on each call |
Derivation: the balance after repeated interest
Each call of addInterest adds r% of the current balance. Write B for the balance after k calls.
Each call multiplies the balance by the same factor, so after n calls the starting balance has been multiplied n times.
With B₀ = 10000, r = 5 and n = 2, B₂ = 10000 × 1.05² = 11025, which matches the trace. Rounding down to whole pence can make later balances a penny or two below the formula.
Inheritance saves effort in two ways. The shared code is written once, in the parent. And when that code is fixed or improved, every subclass benefits at once, with no copies to keep in step. That is the same benefit subroutines bring, applied to whole classes.
Check yourself. List every method a SavingsAccount object can call, using the diagram above.
Show the answer
It can call deposit and withdraw, which it inherits from Account, and addInterest, which SavingsAccount adds itself. Its constructor is also available when the object is created.
Section 4
Overriding and polymorphism
Overriding a method
A subclass can provide its own version of a method that its parent already has. This is overriding. When the method is called on an object of the subclass, the subclass's version runs instead of the parent's. CurrentAccount overrides withdraw so that it can allow an overdraft.
To decide which version runs, the computer starts at the object's own class and searches upwards. The first class that defines the method supplies the version that runs. If no class in the chain defines it, the call is an error.
Figure 22.2 lets you choose an object's class and a method to call. Follow the search up the chain and see which version runs. Then switch on the wrong model, which always runs the parent's version.
Which method runs?
- Version that runs
- Dog.speak()
- Classes searched
- 1
Common mistake: thinking a call always runs the parent class's version. An overridden method replaces the parent's version for objects of the subclass. The search starts at the object's own class, so a Dog that defines speak barks, even though Animal also has a speak method.
The search for a method happens while the program runs, using the class of the actual object, not the type the variable was declared with. A variable declared as an Account may hold a CurrentAccount, and calling withdraw on it runs CurrentAccount's version. This late decision is called dynamic binding, and it is what makes polymorphism work.
Worked example 6: which method runs?
Animal defines speak, eat and describe. Dog inherits from Animal and defines speak and fetch. Puppy inherits from Dog and defines play. Which class's version runs for a Puppy calling speak, eat and fetch?
| Working | Reason |
|---|---|
| The search order is Puppy, then Dog, then Animal | Start at the object's own class and go up |
| speak: not in Puppy, found in Dog, so Dog.speak runs | The first class that defines it wins |
| eat: not in Puppy or Dog, found in Animal | Inherited from the top of the chain |
| fetch: found in Dog, so Dog.fetch runs | Puppy inherits it from its parent |
Extending a parent's method
An overriding method does not have to throw the parent's version away. It can call the parent's version with super, then add to it. A CurrentAccount's monthEnd might call super.monthEnd() to do the common work, then charge a monthly fee. This keeps shared behaviour in one place while letting each subclass add its own.
Abstract classes
Sometimes a parent class exists only to be inherited from. A Shape has an area, but there is no sensible area for a shape in general. Such a class is called abstract: its area method is declared but left for each subclass to fill in, and no plain Shape object can be created.
An abstract class acts as a promise. Every subclass must provide the missing methods, so code that works with shapes can safely call area() on any of them. Python marks this with the abc module; exam questions usually just describe the idea.
Polymorphism
Polymorphism means "many forms". It lets one method call do different things depending on the class of the object it is called on. A program can hold a list of different shapes and call area() on each one. A circle, a rectangle and a triangle each work out their area in their own way.
The program does not need an IF statement that checks each shape's type. Adding a new kind of shape means writing one new class with its own area method; the loop that totals the areas does not change at all. That is why polymorphism makes programs easier to extend.
Worked example 7: polymorphism with shapes
A list holds a Rectangle 3 by 4, a Triangle with base 6 and height 4, and a Square of side 5. Each class overrides area(). Find the total area returned by looping over the list.
| Working | Reason |
|---|---|
| The Rectangle's area() returns 3 × 4 = 12 | Rectangle's own version runs |
| The Triangle's area() returns 6 × 4 ÷ 2 = 12 | Triangle overrides area differently |
| The Square's area() returns 5 × 5 = 25 | Each object uses its own class's version |
| Total = 12 + 12 + 25 = 49 | One loop, three different methods |
Why polymorphism matters
Without polymorphism, a program that handles many kinds of object fills up with IF statements that test each object's type. Every time a new kind is added, every one of those IF statements must be found and changed, and missing one causes a bug.
With polymorphism, the knowledge of how each kind behaves lives in its own class. The rest of the program simply calls the method and trusts the object to do the right thing. New kinds of object can be added by writing one new class, with no other code touched.
Some languages also allow overloading, where one class has several methods with the same name but different parameters. Overloading is chosen by the arguments when the code is compiled, while overriding is chosen by the object's class while the program runs. Exam questions about polymorphism are almost always about overriding.
Check yourself. Puppy is a subclass of Dog, which is a subclass of Animal. Only Animal defines eat. Which version runs for a Puppy calling eat, and how many classes are searched?
Show the answer
Animal's version runs. The search checks Puppy, then Dog, then Animal, so three classes are searched before the method is found.
Section 5
Objects as references
Variables hold references
When an object is created, it is stored somewhere in memory, and the variable holds a reference to it, in effect its address. Assigning one object variable to another copies the reference, not the object. Both variables then refer to the same single object.
Common mistake: thinking assigning an object copies it. After b = a, there are still only one object and two names for it. A change made through b, such as b.deposit(5000), is seen through a too. A separate object needs its own new, or an explicit copy.
Worked example 8: two references to one object
a = new Account("Asha"). Then b = a. Then a.deposit(2000) and b.deposit(5000). What is a.getBalance()?
| Working | Reason |
|---|---|
| a refers to a new account with balance 0 | The constructor creates one object |
| b = a copies the reference, so b refers to the same object | No new object is made |
| a.deposit(2000) and b.deposit(5000) both change that object | Both names lead to one balance |
| a.getBalance() returns 7000 | 2000 + 5000 on the same account |
References explain several things that otherwise seem strange. Passing an object to a subroutine passes the reference, so the subroutine can change the object. Comparing two objects with == often compares the references, so two separate accounts holding the same balance may count as different.
When nothing refers to an object any more, it can never be used again. Languages such as Python and Java then reclaim its memory automatically, a process called garbage collection. In other languages, such as C++, the programmer must free the memory explicitly.
Aggregation and composition
Not every relationship between classes is inheritance. A Bank has many Accounts, and a Car has an Engine. These are "has a" relationships, called association. In aggregation, the parts can exist on their own: an account still exists if the bank object is deleted. In composition, the parts belong to the whole and are destroyed with it.
An object that holds a list of other objects can call their methods in a loop. A Bank object might total every account's balance by calling getBalance on each one, without knowing anything about how each account stores its data.
Aggregation is shown on a class diagram as a line between the two classes, often with a hollow diamond at the end of the whole. Composition uses a filled diamond. The numbers at each end, such as 1 and *, show how many objects take part, so one bank can have any number of accounts.
Worked example 9: an object holding objects
A Bank object holds three accounts with balances 6500, 2000 and 11025. Its method totalHoldings calls getBalance on each. What does it return?
| Working | Reason |
|---|---|
| The bank loops over its list of account references | Aggregation: the bank has accounts |
| It calls getBalance on each account in turn | It uses each account's public method |
| 6500 + 2000 + 11025 = 19525 | Add the three returned balances |
| totalHoldings returns 19525 pence, or £195.25 | The bank never reads a balance directly |
Composition gives an object full control of its parts. A Car might create its own Engine in its constructor, keep it private, and never let other code reach it directly. Other code asks the car to start, and the car tells its engine what to do. This keeps the engine's details hidden inside the car.
Copying an object properly
When a genuine copy is needed, the program must create a new object and copy each attribute across. In Python, the copy module does this. A shallow copy duplicates the outer object but shares any objects it holds, while a deep copy duplicates everything, all the way down. Choosing between them depends on whether the parts should be shared.
The same care applies to lists of objects. Copying a list of accounts gives a new list holding the same account references, so changing an account through the copy still changes the original account. Only the list itself is new.
Check yourself. p = new Point(1, 2), then q = p, then q.x = 5. What is p.x, and why?
Show the answer
p.x is 5. The assignment q = p copied the reference, so p and q refer to the same Point object. Changing x through q changes the only object there is.
Section 6
Designing with objects
Inheritance or aggregation?
Choosing between inheritance and aggregation comes down to the relationship. If B is a kind of A, use inheritance: a savings account is an account. If B has an A, or uses one, use aggregation: a car has an engine, but a car is not an engine. Using inheritance for a "has a" relationship gives a class methods that make no sense.
Common mistake: using inheritance for a "has a" relationship. Making Car a subclass of Engine would give every car an engine's methods, such as setFuelMix, as if the car were the engine. A car has an engine, so it should hold an Engine object as an attribute instead.
A common guideline is to prefer composition over inheritance. Inheritance ties a subclass tightly to its parent, so changes to the parent can break the child. Composition joins objects more loosely, through each other's public methods, which makes designs easier to change.
Object-oriented against procedural programming
Procedural programming organises a program as a sequence of procedures that act on data passed to them. Object-oriented programming organises it as objects that hold their own data and methods. Both can solve the same problems; they differ in how the code is structured.
OOP suits large programs and teams. Encapsulation lets each class be built and tested separately, inheritance reuses code, and polymorphism makes new kinds of object easy to add. Procedural code can be simpler and faster for small tasks, where defining classes would add structure without benefit.
Derivation: why methods belong to the class, not to each object
Suppose each object stores a bytes of attributes, and the code for all the class's methods takes m bytes. If every object carried its own copy of the methods, n objects would need this much memory.
Methods do not change from one object to the next, so the class stores their code once, and each object stores only its attributes.
For 10,000 accounts with a = 24 bytes and m = 4,000 bytes, sharing the methods needs 244,000 bytes instead of 40,240,000. That is why objects carry data, while their behaviour lives in the class.
Where OOP is used
Object-oriented languages include Java, C#, C++ and Python. Graphical interfaces are a natural fit: every button, window and menu is an object with its own data and its own response to a click. Games, simulations and large business systems are usually designed around objects too.
Not every program benefits. A short script that renames some files, or a mathematical calculation with no lasting state, gains little from classes. Many programs mix styles, using objects for the main structure and plain functions for simple tasks.
Worked example 10: memory for many objects
Using the derivation, work out the memory for 10,000 Account objects with 24 bytes of attributes each, sharing 4,000 bytes of method code.
| Working | Reason |
|---|---|
| Attributes: 10,000 × 24 = 240,000 bytes | Each object stores its own attributes |
| Method code: 4,000 bytes, stored once | The methods belong to the class |
| Total = 240,000 + 4,000 = 244,000 bytes | Add the two parts |
| Copying the methods into every object would need 40,240,000 bytes | Every object would carry 4,024 bytes |
Testing object-oriented code
Encapsulated classes are well suited to unit testing. Each class can be tested on its own, by creating an object, calling its methods with chosen values and checking the results through its getters. Testing the refusals matters as much as testing the normal cases, because they are the rules the class exists to enforce.
Subclasses need testing too. Each overridden method needs its own tests, and inherited methods should be checked to make sure they still work with the subclass's data. A subclass that breaks code written for its parent is a design error.
Design patterns are well-known solutions to common design problems in object-oriented code. They give names to recurring arrangements of classes, such as an object that creates other objects, or one that notifies others when it changes. Knowing them helps programmers recognise good designs and talk about them.
Whatever the paradigm, the aim is the same: code that is correct, easy to read and easy to change. Object-oriented programming is one powerful way of reaching that aim for large systems. It works best when classes are small, focused on one job, and connected to each other through clear public methods.
Check yourself. Should a Teacher class inherit from a School class? Explain your answer.
Show the answer
No. A teacher is not a kind of school, so inheritance is wrong. A school has teachers, so the School class should hold a list of Teacher objects, which is aggregation.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Class | A blueprint for objects | Account | Defines attributes and methods once |
| Object | One instance of a class | myAccount | Has its own copy of every attribute |
| Constructor | Method run when an object is created | new(owner), init | Sets the starting values |
| Encapsulation | Private data behind public methods | private balance | Checks can never be skipped |
| Getter and setter | Methods that read or change a private attribute | getBalance() | A setter validates first |
| Inheritance | A subclass takes on a parent's members | SavingsAccount inherits Account | An "is a" relationship |
| Overriding | A subclass replaces a parent's method | CurrentAccount.withdraw | Search starts at the object's own class |
| Polymorphism | One call, different behaviour per class | shape.area() | New classes need no change to the loop |
| Reference | A variable holds an object's address | b = a | Both names share one object |
| Aggregation | One object holds others | A bank has accounts | A "has a" relationship |
Programming task
Programming task: bank accounts with inheritance
Aim
Write Python classes Account and SavingsAccount. Account keeps a private balance in pence, refuses non-positive deposits and any withdrawal that would go below an overdraft limit. SavingsAccount inherits from Account and adds interest, rounded down to whole pence.
Design
Account has a constructor that sets the owner, a zero balance and an overdraft limit. Its deposit and withdraw methods check every request and return True or False, so the caller knows whether it worked. A getter returns the balance; there is no setter for it.
SavingsAccount calls the parent's constructor with super(), stores a rate, and adds an add_interest method that deposits the interest. Because add_interest uses the inherited deposit, the deposit check also applies to interest.
Code
class Account:
def __init__(self, owner, overdraft=0):
self.__owner = owner
self.__balance = 0
self.__overdraft = overdraft
def deposit(self, amount):
if amount <= 0:
return False
self.__balance += amount
return True
def withdraw(self, amount):
if amount <= 0 or self.__balance - amount < -self.__overdraft:
return False
self.__balance -= amount
return True
def get_balance(self):
return self.__balance
class SavingsAccount(Account):
def __init__(self, owner, rate):
super().__init__(owner)
self.__rate = rate
def add_interest(self):
interest = self.get_balance() * self.__rate // 100
if interest > 0:
self.deposit(interest)
a = Account("Asha")
a.deposit(5000)
a.withdraw(2000)
print(a.withdraw(4000), a.deposit(-100), a.get_balance())
s = SavingsAccount("Ben", 5)
s.deposit(10000)
s.add_interest()
s.add_interest()
print(s.get_balance())
The double underscore makes Python hide each attribute from code outside the class, which is how Python marks an attribute private. SavingsAccount reads the balance through get_balance, because even a subclass cannot reach the parent's private attributes directly.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | deposit(5000), withdraw(2000) | balance 3000 | Normal use |
| 2 | then withdraw(4000) | False, balance still 3000 | Refuses an overdrawn withdrawal |
| 3 | then deposit(−100) | False, balance still 3000 | Refuses a negative deposit |
| 4 | Account with overdraft 1000 holding 3000, withdraw(4000) | True, balance −1000 | The limit allows exactly −1000 |
| 5 | SavingsAccount at 5%: deposit(10000), add_interest twice | balance 11025 | Interest compounds |
| 6 | SavingsAccount calls withdraw(500) | True | Inherited methods work |
| 7 | a.__balance = 99 from outside, then a.get_balance() | still 3000 | The private balance cannot be set directly |
Evaluation
All seven tests pass. Tests 2 to 4 show that the checks inside the methods protect the balance, and test 6 shows that inheritance gives SavingsAccount the parent's methods without copying them.
An improvement would add a CurrentAccount subclass that overrides withdraw, and a Bank class that holds a list of accounts and calls a month_end method on each. That would use polymorphism, because each kind of account would handle month_end differently.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. Explain what is meant by a class, an object, an attribute and a method.
Worked solution to Q1
A class is a blueprint that defines a kind of object. An object is one instance of a class. An attribute is a variable that each object holds, and a method is a subroutine that each object can run.
Q2. Describe encapsulation and give one benefit.
Worked solution to Q2
Encapsulation bundles an object's data with its methods and makes the data private, so it can only be reached through public methods. A benefit is that the checks in those methods can never be skipped by other code.
Q3. Explain the difference between inheritance and polymorphism.
Worked solution to Q3
Inheritance lets a subclass take on the attributes and methods of a parent class. Polymorphism lets one method call behave differently depending on the class of the object, usually because subclasses override the method.
Rung 2: Application
Q4. An account opens with 0. It receives deposit(8000), withdraw(3000) and withdraw(6000), with no overdraft. Give the final balance and say which call is refused.
Worked solution to Q4
After deposit(8000) the balance is 8000, and withdraw(3000) leaves 5000. Then withdraw(6000) would take the balance to −1000, so it is refused. The final balance is 5000.
Q5. A SavingsAccount at 10% holds 20000. Find the balance after addInterest() is called twice.
Worked solution to Q5
The first call adds 10% of 20000, which is 2000, giving 22000. The second adds 10% of 22000, which is 2200, giving 24200. The interest compounds because it is worked out on the new balance.
Q6. Using the Animal, Dog and Puppy classes of worked example 6, state which class's version runs when a Dog calls describe.
Worked solution to Q6
The search starts at Dog, which does not define describe. It moves up to Animal, which does, so Animal's version of describe runs. Dog inherits it unchanged.
Q7. A list holds a Rectangle 2 by 7 and a Square of side 4. Each overrides area(). Find the total area.
Worked solution to Q7
The Rectangle's area() returns 2 × 7 = 14, and the Square's returns 4 × 4 = 16. Looping over the list and adding gives 14 + 16 = 30.
Rung 3: Analysis
Q8. x = new Account("Kim"), y = x, then x.deposit(400) and y.withdraw(150). State x.getBalance() and explain.
Worked solution to Q8
The balance is 400 − 150 = 250. The assignment y = x copied the reference, so x and y refer to the same account, and both calls change the one balance.
Q9. Explain why a programmer might give a class a getter but no setter for an attribute.
Worked solution to Q9
The attribute needs to be read by other code, so a getter is provided. But it should never be changed from outside, or only through methods that apply rules, so leaving out the setter makes it read-only.
Q10. A Puppy calls fetch. Puppy does not define it, Dog does, and Animal does not. How many classes are searched, and which version runs?
Worked solution to Q10
The search checks Puppy first, then Dog, where fetch is found, so two classes are searched. Dog's version runs, and Animal is never checked.
Q11. Explain why Car should not inherit from Engine.
Worked solution to Q11
A car is not a kind of engine, so inheritance would give the car an engine's methods as if it were one. A car has an engine, so Car should hold an Engine object as an attribute, which is aggregation.
Rung 4: Stretch
Q12. Using the formula B = B₀(1 + r/100)ⁿ, find the balance of a 4% savings account that starts at 50000 after 3 interest calls, ignoring rounding.
Worked solution to Q12
The factor is 1.04, so B = 50000 × 1.04³. Since 1.04³ = 1.124864, the balance is 50000 × 1.124864 = 56243.2, so 56243 pence once it is rounded down.
Q13. Work out the memory saved by storing methods once for 2,000 objects with 40 bytes of attributes each and 6,000 bytes of method code.
Worked solution to Q13
Shared methods need 2,000 × 40 + 6,000 = 86,000 bytes. Copying the methods into every object would need 2,000 × (40 + 6,000) = 12,080,000 bytes. Sharing saves 11,994,000 bytes.
Q14. Explain how polymorphism lets a program add a new Hexagon shape without changing the loop that totals the areas.
Worked solution to Q14
The loop calls shape.area() on each object and does not check its type. A new Hexagon class only needs its own area method. The same loop then calls Hexagon's version automatically when it meets a hexagon.
Exam practice
Exam technique and worked answer workshop
Definitions in OOP questions must be precise. Say that a class is a blueprint and an object is an instance. Say that encapsulation makes attributes private and gives access through methods. Vague answers, such as "OOP uses objects", earn nothing.
When tracing method calls, keep a separate column for each object's attributes, and remember that b = a gives two names for one object. When deciding which method runs, write out the search order from the object's own class upwards.
When writing a class, include the constructor, mark attributes private, and give every method a clear header. Check that a subclass calls its parent's constructor.
Exam question 1 (4 marks · Paper 02 · about 5 minutes)
Define the terms class, object, attribute and method.
Mark scheme for exam question 1
- B1 a class is a blueprint that defines a type of object
- B1 an object is an instance of a class, created from it
- B1 an attribute is a data item or variable held by each object
- B1 a method is a subroutine that an object can carry out
Exam question 2 (5 marks · Paper 02 · about 7 minutes)
An Account object opens with a balance of 0. Its withdraw method refuses any withdrawal that would take the balance below 0, and deposit refuses amounts that are not positive. The calls deposit(5000), withdraw(2000), withdraw(4000), deposit(−100) are made.
(a) Give the balance after each call. [4]
(b) State the final balance. [1]
Mark scheme for exam question 2
- B1 after deposit(5000): 5000
- B1 after withdraw(2000): 3000
- B1 after withdraw(4000): still 3000, refused
- B1 after deposit(−100): still 3000, refused
- B1 final balance 3000
Exam question 3 (5 marks · Paper 02 · about 7 minutes)
Write a class Account with a private balance and a constructor that sets the balance to 0. Include a deposit method that only accepts positive amounts, and a getter for the balance.
Mark scheme for exam question 3
- B1 class definition with balance declared private
- B1 constructor that sets balance to 0
- B1 public deposit method taking an amount
- M1 deposit checks that the amount is greater than 0
- A1 adds the amount to balance, and getBalance returns balance
Exam question 4 (5 marks · Paper 02 · about 7 minutes)
SavingsAccount inherits from Account and adds addInterest, which deposits r% of the balance.
(a) Explain what inheritance means here. [2]
(b) A SavingsAccount at 5% holds 10000. Calculate the balance after two calls of addInterest. [3]
Mark scheme for exam question 4
- B1 SavingsAccount takes on all of Account's attributes and methods
- B1 and adds its own, such as the rate and addInterest
- B1 first call adds 500, giving 10500
- M1 second call works out 5% of the new balance, 525
- A1 11025
Exam question 5 (6 marks · Paper 01 · about 9 minutes)
A games company is starting a large new game with many kinds of character, written by a team of programmers. Discuss the benefits and drawbacks of using object-oriented programming rather than procedural programming.
Mark scheme for exam question 5
Level 3 (5–6 marks): a balanced discussion of encapsulation, inheritance and polymorphism, each applied to the game and the team, with at least one drawback. The answer reaches a justified conclusion. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): correct benefits of at least two OOP features, with some application to the game. Drawbacks or the conclusion are limited.
Level 1 (1–2 marks): some relevant points, such as that OOP uses objects, with little application. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- each kind of character can be a class, and each character in the game an object
- encapsulation keeps each character's data private, so other code cannot corrupt it
- each class can be written and tested separately by different team members
- inheritance lets characters share common code from a Character parent class
- polymorphism lets the game call update() on every character without checking its type
- new kinds of character can be added without changing existing code
- OOP can add complexity and planning time, and deep inheritance can be hard to follow
- procedural code may be simpler for small tasks, but OOP suits a large team project
Annotated model answer: exam question 5
"Each kind of character, such as a player, an enemy or a shopkeeper, can be a class, and each character in the game an object. Encapsulation keeps each character's health and position private, so another programmer's code cannot set them to impossible values." (Classes and encapsulation, applied.)
"Because each class has a clear interface, team members can write and test their classes separately and combine them later. Inheritance lets every character share movement and collision code from a Character parent class, so that code is written once." (Teamwork and inheritance.)
"Polymorphism lets the main loop call update() on every character without checking its type. Each class overrides update in its own way, so new characters can be added without changing the loop." (Polymorphism and extension.)
"OOP does take more planning, and a deep inheritance hierarchy can become hard to follow. For a large game written by a team, these costs are worth it, so OOP is the better choice." (Drawback and a justified conclusion.)
This answer reaches Level 3 and scores 6 marks. It applies all three main features to the game and weighs them against a real drawback.
Exam question 6 (6 marks · Paper 02 · about 9 minutes)
Shape has a method area(). Rectangle, Triangle and Square inherit from Shape, and each overrides area(). A list holds a Rectangle 3 by 4, a Triangle with base 6 and height 4, and a Square of side 5.
(a) Explain what is meant by overriding. [2]
(b) Explain how polymorphism is used when a loop calls area() on each shape. [2]
(c) Calculate the total area. [2]
Mark scheme for exam question 6
- B1 a subclass provides its own version of a method that its parent has
- B1 that version runs instead of the parent's for objects of the subclass
- B1 the same call, shape.area(), is made on every object in the list
- B1 the version that runs depends on each object's class
- M1 areas 12, 12 and 25
- A1 total 49
Annotated model answer: exam question 6
"(a) Overriding is when a subclass provides its own version of a method that its parent already has. For an object of the subclass, that version runs instead of the parent's." (Both marks: what overriding is and its effect.)
"(b) The loop makes the same call, shape.area(), on every object without checking types. The version that runs depends on each object's class, so each shape works out its area in its own way." (Polymorphism explained.)
"(c) The Rectangle gives 12, the Triangle 6 × 4 ÷ 2 = 12, and the Square 25, so the total is 49." (Working, then the answer.)
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
a = new Account("Asha"), then b = a, then a.deposit(2000) and b.deposit(5000).
(a) State a.getBalance(). [1]
(b) Explain your answer. [2]
(c) State how to make b a separate account. [1]
Mark scheme for exam question 7
- B1 7000
- B1 b = a copies the reference, not the object
- B1 so a and b refer to the same account, and both deposits change it
- B1 create a new object, b = new Account(...)
Exam question 8 (5 marks · Paper 02 · about 7 minutes)
Animal defines speak, eat and describe. Dog inherits from Animal and defines speak and fetch. Puppy inherits from Dog and defines play.
(a) State which class's version runs when a Puppy calls speak, and when it calls eat. [2]
(b) State what happens when an Animal calls fetch, and why. [2]
(c) Give the order in which classes are searched for a Puppy. [1]
Mark scheme for exam question 8
- B1 speak: Dog's version
- B1 eat: Animal's version
- B1 an error, because the method is not found
- B1 Animal is the top of the chain and fetch is defined only in its subclass Dog
- B1 Puppy, Dog, Animal
Connections
Synoptic link
Objects build on the records in Arrays, records, stacks and queues: a record bundles data, and an object bundles data with behaviour. Methods are subroutines, with the parameters and local variables taught in Subroutines and recursion.
Many data structures are naturally written as classes. A stack or a linked list from Linked lists, hash tables, graphs and trees becomes a class with private storage and public push or insert methods. Translators and programming paradigms places OOP alongside procedural, functional and declarative programming.
Synoptic question 1. A Stack class keeps a private array of 100 cells and a private top pointer, with public push and pop methods. Explain how encapsulation protects the stack.
Answer to synoptic question 1
Other code cannot reach the array or the top pointer directly, so it cannot put items in the wrong cell or move the pointer by mistake. Every change goes through push and pop, which check for overflow and underflow, so the stack always stays valid.
Recap
Recap and next step
- A class is a blueprint with attributes and methods; an object is one instance, created by a constructor, with its own attribute values.
- Encapsulation makes attributes private and gives access through public methods, so every check runs; getters read and setters validate.
- A subclass inherits its parent's attributes and methods and adds its own; it calls the parent's constructor with super.
- Overriding replaces a parent's method; the search for a method starts at the object's own class, and polymorphism lets one call act differently per class.
- Variables hold references, so b = a shares one object; aggregation models "has a", while inheritance models "is a".
- OOP suits large team projects through encapsulation, reuse and extension; methods are stored once in the class, not in every object.
Next chapter: Development environments, testing and computational methods covers the tools and tests used to build programs like these, and the methods used to solve problems with them.
For your exam board
OCR A Level Computer Science (H446): this chapter covers object-oriented techniques, classes, objects, methods, attributes, inheritance, encapsulation and polymorphism, in section 2.2.1, Programming techniques, in Component 02. Object-oriented languages as a paradigm are in section 1.2.4, Types of programming language, in Component 01.
AQA A Level Computer Science (7517): classes, objects, instantiation, encapsulation, inheritance, aggregation, composition, polymorphism, overriding and class diagrams appear in the fundamentals of programming section, under the object-oriented programming paradigm, assessed on Paper 1.