Object-oriented Programming (OOP)
Classes and objects, constructors, encapsulation, inheritance, polymorphism and containment, and designing a class from a problem, written in Cambridge pseudocode and in Python.
Classes, objects and constructors
A class is a blueprint. Objects are made from it, and the constructor gives each new object its starting values.
A class is a blueprint, like the plan for a house. It defines:
- the attributes (properties): the data that every object of that kind will have
- the methods: its procedures and functions, which act on the attributes.
An object is one instance of a class, with its own values for the attributes. Making one is called instantiation. One plan can build many houses.
The constructor is a procedure named NEW in Cambridge pseudocode. It runs when an object is created. It gives the attributes their starting values.
Watch out:Call a method with a dot and no CALL: Pupil1.SetMark(78).
CLASS Student PRIVATE Name : STRING PRIVATE Mark : INTEGER PUBLIC PROCEDURE NEW(GivenName : STRING) Name ← GivenName Mark ← 0 ENDPROCEDURE PUBLIC PROCEDURE SetMark(NewMark : INTEGER) IF NewMark >= 0 AND NewMark <= 100 THEN Mark ← NewMark ENDIF ENDPROCEDURE PUBLIC FUNCTION GetMark() RETURNS INTEGER RETURN Mark ENDFUNCTION ENDCLASS DECLARE Pupil1 : Student Pupil1 ← NEW Student("Bat") Pupil1.SetMark(78) OUTPUT Pupil1.GetMark()
One class, many objects
A class is written once, but a program can make many objects from it. Each object keeps its own values.
A class is written once. It is a template: it says which attributes and methods each object of that kind has. It holds no values itself.
Objects are made from it while the program runs, each with NEW. Memory for an object's own values is set aside only when that object is made.
| Class | Object | |
|---|---|---|
| How many | written once | one class can make many |
| Values | holds none | has its own values, in its own memory |
| Made | written in the code | made with NEW while the program runs |
Remember:Changing one object leaves the others alone.
Example:Below, one Student class makes three objects in an array. The loop calls GetMark() on each in turn and outputs 0, 64 and 0.
// Student is the class at the top of this page DECLARE Pupils : ARRAY[1:3] OF Student DECLARE Index : INTEGER Pupils[1] ← NEW Student("Bat") Pupils[2] ← NEW Student("Saraa") Pupils[3] ← NEW Student("Tuya") Pupils[2].SetMark(64) FOR Index ← 1 TO 3 OUTPUT Pupils[Index].GetMark() NEXT Index
Encapsulation: private attributes, public methods
Encapsulation locks an object's data inside it. Other code can reach the data only through the object's public methods.
Encapsulation puts an object's data and the methods that act on it together in one unit. It keeps the attributes private: only the class's own methods can read or change them. The rest of the program uses the public methods.
- A setter changes an attribute. It can check the new value first, so
SetMarkcan refuse 500. - A getter returns an attribute's value.
It is like a bank account: you cannot change the balance yourself. You ask the bank, and the bank checks first.
Remember:No other code can put a Student into an impossible state. The only way in is through the class's own methods.
Designing a class from a scenario
To design a class, ask two questions: what must one object store, and what must it do?
To design a class, read the scenario. Ask what one object must store, and what it must do.
| Part of the class | How to write it |
|---|---|
| each item it stores | a PRIVATE attribute with a data type: STRING for text, INTEGER for a whole number, DATE for a date |
| values known when an object is made | the constructor's parameters |
| any other attribute | gets a starting value |
| a setter | a procedure with one parameter of its attribute's type; it can check the value before storing it |
| a getter | a function with no parameter that returns its attribute |
A class diagram lists three things, from top to bottom:
- the class name
- the attributes, with their types
- the methods.
CLASS Book PRIVATE Title : STRING PRIVATE Author : STRING PRIVATE DateBought : DATE PRIVATE Copies : INTEGER PUBLIC PROCEDURE NEW(GivenTitle : STRING, GivenAuthor : STRING, GivenDate : DATE) Title ← GivenTitle Author ← GivenAuthor DateBought ← GivenDate Copies ← 0 ENDPROCEDURE PUBLIC PROCEDURE SetCopies(NewCopies : INTEGER) IF NewCopies >= 0 AND NewCopies <= 20 THEN Copies ← NewCopies ENDIF ENDPROCEDURE PUBLIC FUNCTION GetTitle() RETURNS STRING RETURN Title ENDFUNCTION PUBLIC FUNCTION GetCopies() RETURNS INTEGER RETURN Copies ENDFUNCTION ENDCLASS
Inheritance
A subclass gets everything its parent class has. Then it can add more, or change some methods.
Inheritance lets you define a new class, the subclass (child), from an existing superclass (parent).
- The subclass automatically has all the parent's attributes and methods.
- It may add its own, or override (replace) some.
Example:A Bus is a Vehicle. In Cambridge pseudocode you write CLASS Bus INHERITS Vehicle. The subclass's constructor calls the parent's constructor with SUPER.NEW(...).
Exam:A class diagram draws each class as a box of attributes and methods. An arrow goes from each subclass to its superclass.
CLASS Vehicle PRIVATE Plate : STRING PUBLIC PROCEDURE NEW(GivenPlate : STRING) Plate ← GivenPlate ENDPROCEDURE PUBLIC FUNCTION Describe() RETURNS STRING RETURN "Vehicle " & Plate ENDFUNCTION ENDCLASS CLASS Bus INHERITS Vehicle PRIVATE Seats : INTEGER PUBLIC PROCEDURE NEW(GivenPlate : STRING, GivenSeats : INTEGER) SUPER.NEW(GivenPlate) Seats ← GivenSeats ENDPROCEDURE ENDCLASS
Polymorphism
One method name can do different things. Each object runs the version written in its own class.
Polymorphism means one method name behaves differently, depending on the class of the object it is called on.
- A subclass overrides a method: it defines its own version with the same name.
- When the method is called, the object's own class decides which version runs.
Example:A loop can call Area() on every shape in a list, without knowing what kind each one is.
| The object's class | What Area() works out |
|---|---|
Circle | πr² |
Rectangle | width × height |
CLASS Shape PUBLIC FUNCTION Area() RETURNS REAL RETURN 0.0 ENDFUNCTION ENDCLASS CLASS Circle INHERITS Shape PRIVATE Radius : REAL PUBLIC PROCEDURE NEW(R : REAL) Radius ← R ENDPROCEDURE // overrides PUBLIC FUNCTION Area() RETURNS REAL RETURN 3.14159 * Radius * Radius ENDFUNCTION ENDCLASS CLASS Rectangle INHERITS Shape PRIVATE Width : REAL PRIVATE Height : REAL PUBLIC PROCEDURE NEW(W : REAL, H : REAL) Width ← W Height ← H ENDPROCEDURE // overrides PUBLIC FUNCTION Area() RETURNS REAL RETURN Width * Height ENDFUNCTION ENDCLASS
Containment (aggregation)
Containment is a "has a" link: one object holds objects of another class. Inheritance is an "is a" link.
Containment, also called aggregation, is when one class has objects of another class as attributes. A Team has Players, and a Library has Books.
| Test sentence | Relationship | Example |
|---|---|---|
| "has a" | Containment (aggregation) | a Team has Players |
| "is a" | Inheritance | a Bus is a Vehicle |
Watch out:A Team is not a Player. So Team and Player are containment, not inheritance.
The contained objects are objects in their own right, made from their own class. So a Player can be created and used without any Team.
CLASS Team PRIVATE TeamName : STRING // HAS Players PRIVATE Players : ARRAY[1:11] OF Player ENDCLASS
OOP in Python for Paper 4
Paper 4 needs real program code, so learn how the same class is written in Python.
Paper 4 is answered in Python, Java or Visual Basic. So you must also write classes in a real language. Below is this page's Student class in Python.
| Idea | Pseudocode | Python |
|---|---|---|
| constructor | NEW | always __init__: init with two underscores on each side |
| private attribute | PRIVATE Mark : INTEGER | a name that begins with two underscores, such as __Mark |
| data types | declared | no declarations: give each attribute's type in a comment, as the mark schemes do |
| subclass | CLASS Bus INHERITS Vehicle | class Bus(Vehicle): |
| call the parent's constructor | SUPER.NEW | super() |
In Python, every method's first parameter is self: the object it works on.
Watch out:Code outside the class that reads a private attribute gets an AttributeError.
class Student:
# self.__Name : STRING
# self.__Mark : INTEGER
def __init__(self, GivenName):
self.__Name = GivenName
self.__Mark = 0
def SetMark(self, NewMark):
if NewMark >= 0 and NewMark <= 100:
self.__Mark = NewMark
def GetMark(self):
return self.__Mark
Pupil1 = Student("Bat")
Pupil1.SetMark(int(input("Mark? ")))
Mark = Pupil1.GetMark()
print("Pupil1's mark is", Mark)KEY TERMS
CHECK YOURSELF
1.Why are class attributes usually private?
2.A subclass provides its own version of a method that its superclass already has. This is:
3.Which of these is containment (aggregation)?
4.In Cambridge pseudocode, how does a Bus constructor set the Plate it inherits from Vehicle?
5.The class Book has the attribute Copies : INTEGER. Which is its getter?
6.Which of these is a difference between a class and an object?
7.Which OOP term is described as "an occurrence of an object"?
8.In Python, how does the class Student make its attribute Mark private?
9.Where are a class's attributes declared in Cambridge pseudocode?