CIE AS & A Level Computer Science, section 20.1 (Programming paradigms)
Class diagram
A class diagram shows a class as a box with three parts: the name, the attributes, and the methods. An arrow from a child to a parent shows inheritance.
- means private, + means public.
In CIE pseudocode
CLASS Account
PRIVATE Owner : STRING
PRIVATE Balance : REAL
PUBLIC PROCEDURE NEW(OwnerName : STRING)
Owner ← OwnerName
Balance ← 0
ENDPROCEDURE
PUBLIC PROCEDURE Deposit(Amount : REAL)
Balance ← Balance + Amount
ENDPROCEDURE
PUBLIC FUNCTION GetBalance() RETURNS REAL
RETURN Balance
ENDFUNCTION
ENDCLASS
CLASS SavingsAccount INHERITS Account
PRIVATE Rate : REAL
PUBLIC PROCEDURE NEW(OwnerName : STRING, R : REAL)
SUPER.NEW(OwnerName)
Rate ← R
ENDPROCEDURE
PUBLIC PROCEDURE AddInterest()
CALL Deposit(GetBalance() * Rate)
ENDPROCEDURE
ENDCLASS
DECLARE Saver : SavingsAccount
Saver ← NEW SavingsAccount("Aisha", 0.05)
Python
class Account:
def __init__(self, owner):
self.__owner = owner
self.__balance = 0.0
def deposit(self, amount):
if amount > 0: # encapsulation: validation
self.__balance += amount
def get_balance(self):
return self.__balance
class SavingsAccount(Account): # inheritance
def __init__(self, owner, rate):
super().__init__(owner) # call the parent constructor
self.__rate = rate
def add_interest(self):
self.deposit(self.get_balance() * self.__rate)
saver = SavingsAccount("Aisha", 0.05)
saver.deposit(200)
saver.add_interest()
print(saver.get_balance()) # 210.0
Containment example
class Customer:
def __init__(self, name):
self.name = name
self.accounts = [] # a Customer contains Account objects
c = Customer("Aisha")
c.accounts.append(Account("Aisha"))
Steps in a design
- Find the things (nouns) in the problem: these are classes.
- Find their data (attributes) and actions (methods).
- Decide on inheritance (is-a) and containment (has-a).
- Draw the diagram, then write and test each class.
Common mistake: forgetting to call the parent constructor in a child class, so the inherited attributes are never set. Also, private attributes cannot be used directly in the child class: use the parent's methods.
Exam tip: in a design question, draw boxes with name, attributes and methods, with an arrow to the parent for inheritance. In code, check constructor, private attributes and methods are all there.
Check yourself
What goes in the three sections of a class diagram?
The class name, its attributes and its methods.
Why does a child class constructor call the parent constructor?
So the inherited attributes are set up with their starting values.
Give an example of a containment relationship.
A Car object that contains an Engine object.