A Level · Topic 20.1
A-Level Computer Science 9618 / Topic 20 / A2

Classes, objects and inheritance.

Object-oriented programming builds a program from objects that hold their own data and know how to process it. Learn the OOP vocabulary the examiners expect, write classes with private attributes, constructors, getters and setters in 9618 pseudocode, and use inheritance, polymorphism and containment to design a solution.

The key idea

A class is a blueprint that defines the attributes (properties: the data) and methods (procedures and functions) of a type of object. An object is an instance of a class, created by calling its constructor (NEW). Encapsulation keeps attributes PRIVATE so they can only be read or changed through PUBLIC getters and setters. Inheritance lets a subclass take on the attributes and methods of its superclass and add its own; polymorphism lets a subclass override an inherited method so the same method call behaves differently for different classes. Containment (aggregation) is when an object of one class holds objects of another class as attributes.

A class diagram: inheritance (hollow arrow) and containment (diamond) Shape Rectangle Circle Drawing - Name : STRING + Area() : REAL - Width : REAL - Height : REAL + Area() : REAL - Radius : REAL + Area() : REAL - Shapes[1:20] + TotalArea() Rectangle and Circle INHERIT from Shape and override Area() A Drawing CONTAINS Shape objects - private, + public
Fig. 1: Rectangle and Circle inherit from Shape (is-a); a Drawing contains Shape objects (has-a)
Section 01

Classes, objects and encapsulation.

In the 9618 pseudocode a class is written between CLASS and ENDCLASS. The constructor is always a procedure called NEW, and the keywords PUBLIC and PRIVATE set who may use each attribute and method.

CLASS Account
    PRIVATE AccountID : STRING
    PRIVATE Balance : REAL
    PUBLIC PROCEDURE NEW(GivenID : STRING)
        AccountID ← GivenID
        Balance ← 0
    ENDPROCEDURE
    PUBLIC FUNCTION GetBalance() RETURNS REAL
        RETURN Balance
    ENDFUNCTION
    PUBLIC PROCEDURE Deposit(Amount : REAL)
        IF Amount > 0 THEN
            Balance ← Balance + Amount
        ENDIF
    ENDPROCEDURE
    PUBLIC FUNCTION Withdraw(Amount : REAL) RETURNS BOOLEAN
        IF Amount > 0 AND Amount <= Balance THEN
            Balance ← Balance - Amount
            RETURN TRUE
        ELSE
            RETURN FALSE
        ENDIF
    ENDFUNCTION
ENDCLASS

DECLARE MyAccount : Account
MyAccount ← NEW Account("A101")
MyAccount.Deposit(50)
OUTPUT MyAccount.GetBalance()
TermMeaning, using the Account class
Classthe blueprint: Account defines what every account stores and can do
Object / instanceMyAccount is one instance of Account, with its own AccountID and Balance
Attribute (property)a data item of the object: AccountID, Balance
Methoda procedure or function in the class: NEW, GetBalance, Deposit, Withdraw
Constructorthe method NEW, run when the object is created, which initialises the attributes
Gettera method that returns the value of a private attribute: GetBalance
Settera method that changes a private attribute, usually after checking the new value: Deposit only accepts a positive amount
Encapsulationattributes and methods are bundled together, and the attributes are PRIVATE so other code cannot set Balance to a nonsense value directly
Worked example Trace method calls
After the code above, these statements run: OUTPUT MyAccount.Withdraw(80), OUTPUT MyAccount.Withdraw(20), MyAccount.Deposit(-10), OUTPUT MyAccount.GetBalance(). What is output?
  1. After the constructor and Deposit(50), Balance = 50.
  2. Withdraw(80): 80 <= 50 is false, so the balance is unchanged and FALSE is output.
  3. Withdraw(20): 20 > 0 and 20 <= 50, so Balance becomes 30 and TRUE is output.
  4. Deposit(-10): the amount is not greater than 0, so nothing changes.
  5. GetBalance() returns 30.
Answer: FALSE, TRUE, 30. Because Balance is PRIVATE, the only way to change it is through methods that validate the change: that is the point of encapsulation.
Your turn
Write a PUBLIC getter for AccountID and explain why a statement MyAccount.Balance ← 1000 in the main program would be rejected.
Examiner trap

A class and an object are not the same thing. The class is the definition (written once); an object is an instance created from it with NEW, and there can be many objects of one class, each with its own attribute values.

Section 02

Inheritance and polymorphism.

A subclass is declared with INHERITS. It gets every attribute and method of the superclass, adds its own, and can override a method by redefining it with the same name. Its constructor calls the superclass constructor with SUPER.NEW.

CLASS Shape
    PRIVATE Name : STRING
    PUBLIC PROCEDURE NEW(GivenName : STRING)
        Name ← GivenName
    ENDPROCEDURE
    PUBLIC FUNCTION GetName() RETURNS STRING
        RETURN Name
    ENDFUNCTION
    PUBLIC FUNCTION Area() RETURNS REAL
        RETURN 0
    ENDFUNCTION
ENDCLASS

CLASS Rectangle INHERITS Shape
    PRIVATE Width : REAL
    PRIVATE Height : REAL
    PUBLIC PROCEDURE NEW(GivenName : STRING, GivenWidth : REAL, GivenHeight : REAL)
        SUPER.NEW(GivenName)
        Width ← GivenWidth
        Height ← GivenHeight
    ENDPROCEDURE
    PUBLIC FUNCTION Area() RETURNS REAL
        RETURN Width * Height
    ENDFUNCTION
ENDCLASS

CLASS Circle INHERITS Shape
    PRIVATE Radius : REAL
    PUBLIC PROCEDURE NEW(GivenName : STRING, GivenRadius : REAL)
        SUPER.NEW(GivenName)
        Radius ← GivenRadius
    ENDPROCEDURE
    PUBLIC FUNCTION Area() RETURNS REAL
        RETURN 3.142 * Radius * Radius
    ENDFUNCTION
ENDCLASS

DECLARE Shapes : ARRAY[1:3] OF Shape
DECLARE Index : INTEGER
Shapes[1] ← NEW Rectangle("R1", 4, 2.5)
Shapes[2] ← NEW Circle("C1", 2)
Shapes[3] ← NEW Rectangle("R2", 3, 3)
FOR Index ← 1 TO 3
    OUTPUT Shapes[Index].GetName(), " ", Shapes[Index].Area()
NEXT Index
Worked example Predict the output
What does the loop at the end of the code output?
  1. Index 1: a Rectangle, so Rectangle's Area runs: 4 * 2.5 = 10. Output R1 10.
  2. Index 2: a Circle, so Circle's Area runs: 3.142 * 2 * 2 = 12.568. Output C1 12.568.
  3. Index 3: a Rectangle: 3 * 3 = 9. Output R2 9.
  4. GetName is the inherited Shape method in every case.
Answer: R1 10, C1 12.568, R2 9. Shape's own Area (returning 0) is never used, because every object here belongs to a subclass that overrides it.
Examiner trap

Inheritance and polymorphism are different marks. Inheritance is the subclass receiving the superclass's attributes and methods; polymorphism is a method with the same name behaving differently in different classes (by overriding).

Stage 1 · Learn

Check what the sim just showed you

Four quick checks. Each correct answer earns XP and records this skill on your profile.

Quick check+10 XP

What is an object?

Quick check+10 XP

What is the name of a constructor in 9618 pseudocode?

Quick check+10 XP

Why are attributes usually declared PRIVATE?

Quick check+10 XP

The same method call Area() gives different results for a Circle and a Rectangle. What is this?

Section 03

Containment and class design.

Not every relationship is inheritance. If an object has other objects as parts, use containment (aggregation): the container holds them as attributes, often in an array.

CLASS Drawing
    PRIVATE Shapes : ARRAY[1:20] OF Shape
    PRIVATE NumShapes : INTEGER
    PUBLIC PROCEDURE NEW()
        NumShapes ← 0
    ENDPROCEDURE
    PUBLIC FUNCTION AddShape(NewShape : Shape) RETURNS BOOLEAN
        IF NumShapes < 20 THEN
            NumShapes ← NumShapes + 1
            Shapes[NumShapes] ← NewShape
            RETURN TRUE
        ELSE
            RETURN FALSE
        ENDIF
    ENDFUNCTION
    PUBLIC FUNCTION TotalArea() RETURNS REAL
        DECLARE Total : REAL
        DECLARE Index : INTEGER
        Total ← 0
        FOR Index ← 1 TO NumShapes
            Total ← Total + Shapes[Index].Area()
        NEXT Index
        RETURN Total
    ENDFUNCTION
ENDCLASS
Design stepWhat to look for in the scenario
Classesthe main nouns: things the system stores data about (Shape, Drawing, Member, Book)
Attributesthe data each thing has; make them PRIVATE and choose a data type for each
Methodswhat each thing does or what is done to it (verbs); a constructor, getters and setters, plus processing methods
Inheritance"is a": several classes share attributes and methods, so put the shared part in a superclass
Containment"has a": one object is made up of, or holds, objects of another class
Worked example Design classes from a description
A library lends items. Every item has a title, an ID and an on-loan flag. Books also have an author; DVDs have a running time in minutes. A member has a name and can borrow up to 5 items. Identify the classes, their relationships and suitable attributes.
  1. Shared data (title, ID, on loan) goes in a superclass Item: PRIVATE Title : STRING, PRIVATE ItemID : STRING, PRIVATE OnLoan : BOOLEAN, with getters and a setter for OnLoan.
  2. Book INHERITS Item adding PRIVATE Author : STRING; DVD INHERITS Item adding PRIVATE RunTime : INTEGER. Each constructor calls SUPER.NEW(...).
  3. Member has PRIVATE Name : STRING and contains items: PRIVATE Borrowed : ARRAY[1:5] OF Item and PRIVATE NumBorrowed : INTEGER.
  4. Member methods: NEW, Borrow(NewItem : Item) RETURNS BOOLEAN (FALSE if NumBorrowed = 5 or the item is on loan) and Return.
Answer: Item is the superclass of Book and DVD (inheritance, is-a); Member contains up to 5 Item objects (containment, has-a). Because Borrowed is an ARRAY OF Item, a member can borrow both books and DVDs.
Your turn
A Drawing holds a Rectangle of 4 by 2.5 and a Circle of radius 2 (as above). What does TotalArea() return?
Examiner trap

Do not use inheritance for a has-a relationship. A Drawing is not a kind of Shape, so CLASS Drawing INHERITS Shape is wrong; a Drawing contains Shapes.

Stage 2 · Exam

Exam-style questions

Unlocks once the four checks above are done. Worth more XP, written to A Level Paper 3 and Paper 4 standard.

Finish the four checks above to unlock the exam questions
Exam style+20 XP

Which line correctly begins a subclass Lorry of the class Vehicle?

Exam style+20 XP

Inside the constructor of Lorry, how is the constructor of Vehicle called?

Exam style+20 XP

A Team object stores an array of Player objects. Which relationship is this?

Exam style+20 XP

Which statement correctly creates an object of the class Circle?

Skill unlocked

Object-oriented programming, encapsulated.

This skill is now recorded on your profile. Keep the chain going.

-Rank -Level -Score -Topics
Go deeper · practice
Six original Cambridge-style questions
OOP terminology, writing classes with constructors, getters and setters, inheritance with SUPER, polymorphism and containment.