Teachers' Portal  /  A-Level Computer Science 9618  /  Further Programming  /  Object-oriented programming
Lesson pack · A-Level Computer Science 9618 · 20.1 · A Level (A2)

Object-oriented programming

Classes, objects and inheritance. Object-oriented programming builds a program from objects that hold their own data and know how to process it.

Student lesson Lab, full screen
At a glance

The shape of the lesson

Topic
Further Programming
Syllabus reference
Cambridge International AS and A Level Computer Science 9618, 20.1
Level
A Level (A2)
Duration
45 minutes, lab-led; stretches to a 60 minute block (see the contingency notes)
Position in topic
Lesson 2 of 4 in Further Programming; follows Low-level, imperative and declarative paradigms; leads into Serial, sequential and random file processing
Central model
Fig. 1: Rectangle and Circle inherit from Shape (is-a); a Drawing contains Shape objects (has-a)
Cooperative structure
Assessment
Stage 1 check and the exam-style plenary from the student lesson, plus the worksheet as the exit task
Learning objectives

By the end of the lesson, learners can

Section by section
  • Classes, objects and encapsulation: In the 9618 pseudocode a class is written between CLASS and ENDCLASS.
  • Inheritance and polymorphism: A subclass is declared with INHERITS.
  • Containment and class design: Not every relationship is inheritance.
Key points to leave on the board
  • CLASS Name ... ENDCLASS; attributes PRIVATE with a data type; methods PUBLIC unless told otherwise.
  • Constructor = PUBLIC PROCEDURE NEW(...) that sets every attribute; create objects with Obj ← NEW Name(...).
  • Subclass: CLASS Sub INHERITS Super, and call SUPER.NEW(...) first in its constructor.
  • Is-a means inheritance; has-a means containment; same method name, different behaviour means polymorphism.
The core visual model

One picture every idea returns to

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)
Lesson sequence

Forty-five minutes, phase by phase

TimePhaseWhat happens in the roomGrouping
0 to 5 minHook: predictOpen with the question in the title, Classes, objects and inheritance.. Object-oriented programming builds a program from objects that hold their own data and know how to process it. Put the figure on the board: it is the one picture every idea in the lesson returns to.Whole class, then pairs
5 to 13 minTeach and check: Classes, objects and encapsulationIn the 9618 pseudocode a class is written between CLASS and ENDCLASS. Model the worked example Trace method calls on the board, one line at a time. Your turn: Write a PUBLIC getter for AccountID and explain why a statement MyAccount.Balance ← 1000 in the main program would be rejected.Whole class, then pairs
13 to 21 minTeach and check: Inheritance and polymorphismA subclass is declared with INHERITS. Model the worked example Predict the output on the board, one line at a time.Pairs
21 to 30 minTeach and check: Containment and class designNot every relationship is inheritance. Model the worked example Design classes from a description on the board, one line at a time. Your turn: A Drawing holds a Rectangle of 4 by 2.5 and a Circle of radius 2 (as above). What does TotalArea() return?Connect-Extend-Challenge
30 to 36 minCheckThe four Stage 1 questions from the student lesson, answered on mini whiteboards or by show of fingers. Re-teach the one most get wrong.Individual, then whole class
36 to 43 minPlenaryThe exam-style questions from Stage 2, one at a time: thirty seconds alone, then a random call. The feedback lines in the key give the examiner's wording.Individual, random call
43 to 45 minExit and homeworkSet the worksheet below (6 questions, 24 marks). Learners self-assess against the objectives before they leave.Individual
Timing and contingency

Protect the parts that carry the learning

The sequence carries about fifty minutes of material, so the lab is driven by one student while the class predicts rather than explored freely. Times are a guide.

Protected: the check at 30 minutes. It is the only individual read on whether the key idea landed, and it is not cut.

Cut first if the build overruns: the last check in Containment and class design, never the check or the plenary.

In a 60 minute block: run worksheet questions 1 to 3 in class as a Rally Coach set and model both the hardest worked example and its check live.

Running the cooperative task

Connect-Extend-Challenge

After the new idea, each student writes three lines: how it connects to what they knew, how it extends their thinking, and what still challenges them. Pairs compare, then the challenges become the plenary.

The full structure, with its variations and the other twelve, is on the cooperative-learning page.

Examiner traps to pre-empt

What to head off, and how

Trap learners fall intoTeaching move that pre-empts it
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.
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).
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.
Worksheet

Object-oriented programming: worksheet

6 questions, 24 marks. Written in the style of the papers; no past paper question is reproduced.

NameClassDate
Q1 · recall[4 marks]

Explain the meaning of each of these OOP terms: (a) instance (b) encapsulation (c) getter (d) inheritance.

Q2 · write[6 marks]

A class Pupil has private attributes PupilName (a string) and Score (an integer). Write pseudocode for the class, including: a constructor that takes the name and sets Score to 0; a getter for Score; a setter SetScore that only accepts a score from 0 to 100 inclusive.

Q3 · write[4 marks]

A class Prefect inherits from Pupil and has an extra private attribute Duty (a string). Write the class header, the attribute declaration and the constructor, which takes a name and a duty.

Q4 · trace[3 marks]

Using the Pupil class from question 2, state the output of:

P1 ← NEW Pupil("Amir")
P1.SetScore(72)
P1.SetScore(130)
OUTPUT P1.GetScore()
P2 ← NEW Pupil("Bea")
OUTPUT P2.GetScore()
Q5 · explain[3 marks]

Explain, with an example, what is meant by polymorphism.

Q6 · analysis[4 marks]

A garage system records vehicles. Every vehicle has a registration and a year. Cars also have a number of doors and vans have a load capacity. A garage stores up to 50 vehicles. Describe a suitable class design, naming the classes, their relationships and the attributes of each.

Answer key and marking notes
Q1 · 4 marks
  • (a) An object created from a class, with its own values for the class's attributes.
  • (b) Bundling attributes and methods together in a class, and hiding the attributes (PRIVATE) so they can only be accessed through the class's methods.
  • (c) A method that returns the value of a (private) attribute.
  • (d) A subclass takes on the attributes and methods of its superclass and can add its own or override them.
Q2 · 6 marks
  • CLASS Pupil ... ENDCLASS.
  • PRIVATE PupilName : STRING and PRIVATE Score : INTEGER.
  • PUBLIC PROCEDURE NEW(GivenName : STRING) setting PupilName ← GivenName and Score ← 0, ENDPROCEDURE.
  • PUBLIC FUNCTION GetScore() RETURNS INTEGER / RETURN Score / ENDFUNCTION.
  • PUBLIC PROCEDURE SetScore(NewScore : INTEGER) with IF NewScore >= 0 AND NewScore <= 100 THEN Score ← NewScore ENDIF.
  • ENDPROCEDURE and correct use of PUBLIC / PRIVATE throughout.
Q3 · 4 marks
  • CLASS Prefect INHERITS Pupil.
  • PRIVATE Duty : STRING.
  • PUBLIC PROCEDURE NEW(GivenName : STRING, GivenDuty : STRING) calling SUPER.NEW(GivenName).
  • Duty ← GivenDuty, ENDPROCEDURE, ENDCLASS.
Q4 · 3 marks
  • SetScore(72) is accepted, so P1's Score is 72.
  • SetScore(130) is rejected by the setter, so P1's Score stays 72: output 72.
  • P2 is a separate instance whose constructor set Score to 0: output 0.
Q5 · 3 marks
  • A method in a subclass has the same name as a method in the superclass but a different implementation (it overrides it).
  • The same method call behaves differently depending on the class of the object it is called on.
  • Example: Shape has Area(); Circle and Rectangle override Area(), so calling Area() on each object in an array of Shape calculates the correct area for each.
Q6 · 4 marks
  • Superclass Vehicle with PRIVATE Registration : STRING and PRIVATE Year : INTEGER (with constructor and getters).
  • Car INHERITS Vehicle adding PRIVATE NumDoors : INTEGER; Van INHERITS Vehicle adding PRIVATE Capacity : REAL.
  • Garage contains vehicles: PRIVATE Vehicles : ARRAY[1:50] OF Vehicle and a count of vehicles stored.
  • Car and Van use inheritance (is-a); Garage uses containment (has-a).
Quiz

6 multiple-choice questions on this lesson

From the topic question bank. Assign them in the app for a marked score in your gradebook, or run the topic as a class game.

Q11 mark

Which statement about classes and objects is correct?

  • AMany objects can be created from one class, each with its own attribute values
  • BA class is created from an object by calling the constructor NEW
  • CEach class can only ever have one object created from it
  • DObjects share one set of attribute values with every other object of the class
Q21 mark

The Account class from the lesson has a constructor that sets Balance to 0, Deposit that only adds a positive amount, and Withdraw that only succeeds if Amount > 0 AND Amount <= Balance, returning TRUE or FALSE.

MyAcc ← NEW Account("B2")
MyAcc.Deposit(40)
OUTPUT MyAcc.Withdraw(50)
MyAcc.Deposit(25)
OUTPUT MyAcc.Withdraw(65)
OUTPUT MyAcc.GetBalance()
What is output?

  • AFALSE, TRUE, 0
  • BFALSE, TRUE, 65
  • CTRUE, TRUE, -10
  • DFALSE, FALSE, 65
Q31 mark

Cars and buses share a registration and a year, so the classes Car and Bus are designed with a class Vehicle. A Depot can hold up to 40 vehicles. Which describes the relationships?

  • ACar and Bus inherit from Vehicle; Depot contains Vehicle objects
  • BVehicle inherits from Car and Bus; Depot contains Vehicle objects
  • CCar and Bus inherit from Vehicle; Depot inherits from Vehicle
  • DCar and Bus contain Vehicle objects; Depot inherits from Car and Bus
Q41 mark

What is the main purpose of a setter method?

  • ATo change a private attribute, usually after checking the new value is valid
  • BTo return the value of a private attribute to the calling code
  • CTo create a new object and give its attributes their first values
  • DTo redefine a method inherited from the superclass
Q51 mark

Using the Shape, Rectangle and Circle classes from the lesson (Shape's Area returns 0, Rectangle's returns Width * Height, Circle's returns 3.142 * Radius * Radius):

DECLARE D : Drawing
D ← NEW Drawing()
D.AddShape(NEW Rectangle("R1", 4, 3))
D.AddShape(NEW Circle("C1", 2))
D.AddShape(NEW Rectangle("R2", 1, 1))
OUTPUT D.TotalArea()
What is output?

  • A25.568
  • B0
  • C13
  • D19.284
Q61 mark

CLASS Animal
    PRIVATE Name : STRING
    PUBLIC PROCEDURE NEW(GivenName : STRING)
        Name ← GivenName
    ENDPROCEDURE
    PUBLIC FUNCTION Speak() RETURNS STRING
        RETURN "..."
    ENDFUNCTION
ENDCLASS

CLASS Dog INHERITS Animal
    PRIVATE Breed : STRING
    PUBLIC PROCEDURE NEW(GivenName : STRING, GivenBreed : STRING)
        Name ← GivenName
        Breed ← GivenBreed
    ENDPROCEDURE
    PUBLIC FUNCTION Speak() RETURNS STRING
        RETURN "Woof"
    ENDFUNCTION
ENDCLASS
Which is the error in this code?

  • AName ← GivenName in Dog's constructor: it should be SUPER.NEW(GivenName)
  • BBreed ← GivenBreed: Breed must be declared PUBLIC to be set
  • CDog's Speak has the same name as Animal's Speak, which is not allowed
  • DCLASS Dog INHERITS Animal should be CLASS Animal INHERITS Dog
Quiz key
Q1: A

The class is the blueprint; each object is an instance created from it with NEW and holds its own attribute values. NEW creates objects from a class, not the other way round, there is no limit of one object per class, and two Account objects keep separate balances rather than sharing one.

Q2: A

After Deposit(40) the balance is 40, so Withdraw(50) fails (FALSE). Deposit(25) makes 65, and Withdraw(65) succeeds because 65 <= 65, leaving 0. 65 forgets that the successful withdrawal reduced the balance, -10 ignores the check in Withdraw, and FALSE for the second call treats <= as <.

Q3: A

A car is a vehicle and a bus is a vehicle, so the shared attributes go in the superclass Vehicle and Car and Bus inherit from it; a depot has vehicles, so it contains them, for example in an ARRAY[1:40] OF Vehicle. The superclass does not inherit from its subclasses, a depot is not a kind of vehicle, and a car does not contain a vehicle.

Q4: A

A setter changes a private attribute, and can validate the new value first, which is the benefit of encapsulation. Returning the value is a getter, creating and initialising an object is the constructor NEW, and redefining an inherited method is overriding.

Q5: A

Polymorphism means each call to Area() runs the overriding version: 4 × 3 = 12, 3.142 × 2 × 2 = 12.568 and 1 × 1 = 1, giving 25.568. 0 assumes Shape's own Area runs because the array is declared OF Shape, 13 leaves out the circle, and 19.284 uses 3.142 × 2 without squaring the radius.

Q6: A

Name is PRIVATE to Animal, so Dog's constructor cannot set it directly; it must call the superclass constructor with SUPER.NEW(GivenName). Breed is Dog's own attribute, so its constructor may set it while it stays PRIVATE, redefining Speak is overriding (polymorphism), which is allowed, and the subclass is correctly named first before INHERITS.

Slides

Slides for this lesson

A projectable deck for every pack is on the way. Until then, present the student lesson full screen: its sections, figure and lab tabs follow the same order as the plan above.

Also for this topic

Everything else you can use

Original work by the TheLucidSTEM team. The worksheet items are written in the style of the papers; no past paper question is reproduced.
Previous lessonLow-level, imperative and declarative paradigms