CS39 : Programming with objects

This section is about programming paradigms and how to program using objects and, to be honest, is probably one of the most important sections in this year since all the other programming stuff uses the concepts you will learn here. Pay attention!

We are learning ...
  • About different programming paradigms
  • About the concepts of Object Oriented Programming
  • Practical methods of creating and managing objects
So that we can ...
  • List / describe examples of and the need for different programming paradigms
  • Understand the specific characteristics of object oriented programming paradigms
  • Be familiar with the concept of
    - Class
    - Object
    - Instantiation
    - Encapsulation
    - Inheritance
    - Public, private and protected specifiers
    - Polymorphism
    - Aggregation (association and composition)
    - Overriding
    - Abstract, virtual and static methods
  • Be familiar with OOP design principles
    - Encapsulate what varies
    - Favour composition over inheritance
    - Program to interfaces, not implementation
  • Write object oriented programs
  • Draw and interpret class diagrams
    - Single inheritance
    - Public, private (-) and protected (#) specifiers

Activity 1 What is a programming paradigm (and can I use some)?

In a nutshell, a programming paradigm (pronounced 'paradime') is a fundamental style of computer programming, a way of building the structure and the individual elements of computer programs.

Task 1.1
 Paradigm Shift
World Wide Web

What are the major programming paradigms? Unfortunately, there is no definitive list or definition. Using the following Wikipedia article, research the following programming paradigms ...
  • Imperative
  • Structural
  • Procedural
  • Event Driven
  • Declarative
  • Functional
  • Object Oriented
You should attempt to come up with a definition, example and application of each programming paradigm. The ones in bold are considered by some to be the main programming paradigms. What is your view (if you have one)?

OUTCOME : A table containing a summary of each programming paradigm.

So, where are there so many programming paradigms? Why might we want to cook an egg in so many different ways?

Imperative programming

Describes step by step exactly the procedure to be followed in order to solve a problem.  The efficiency of the solution depends on the experience and skill of the programmer in determining the algorithm to solve the problem.

Task 1.2
 Code examples
World Wide Web

Find some actual code examples from the following imperative programming languages.
  • Pascal
What are the common features of each language?

OUTCOME : Four short scripts, one for each imperative language including a statement of how they are similar.

Declarative programming

Describes the problem to be solved but does not specify the method of reaching the solution (control flow).  It is up to the language to determine the best method of reaching the solution. There is a free declarative programming environment called SWI-Prolog which is available as a standard installer or a portable app.

Click to visit SWI-Prolog Website

Task 1.3
 Adventure game

You have actually already used a declarative programming language if you have done any work with SQL. However, how about something a little more challenging? Strictly, you don't really need to do this, but it's a bit of fun and might give you some ideas for a project ...

Make sure you have access to SWI Prolog

If you haven't already, download SWI Prolog from the official website. When you run it, you will be presented with a REPL (a little like IDLE). Don't try to use it without ...

Download and follow the tutorial

Download Logic Programming tutorial save this in a suitable place in your documents. Spend at least an hour following this tutorial - there are lots of new and exciting things to learn. Take your time.

Play the adventure game!

When you reach the end of the tutorial, you will find an old style, text based adventure game! Feel free to type it in or you can download Adventure Game instead. Play the game, but, try not to peak at the script - you will find the answer in there if you look carefully!

OUTCOME : A happy office worker and a little knowledge about declarative programming. Oh, and a print out of the Adventure game for your notes.

Functional programming

Treats problems like mathematical functions and solves them using a variety of mathematical techniques.  These are actually considered a subset of declarative languages. One of the most common functional programming languages is Haskell. It's hard.
Click to visit the Haskell homepage

Task 1.4
 Haskell in the browser

The official Haskell website has a tutorial on the homepage. A simpler version of this is on the Try Haskell website. All you need to do is type help at the prompt and follow the instructions to get some experience of what a functional programming language is.

OUTCOME : Nothing specific, just experience.

However, if you are studying the AQA exam board specification, you will be learning about Functional Programming in a future topic! Looking forward to that!

So, what's the difference?

As we are focusing on Object Oriented Programming, let's compare the same problem solved using a simple, structured and an object oriented approach. Enter the chatbot!

Click to enlarge

You can download the scripts from the lesson resources - have a play. Which one (if any) do you prefer? What's the advantage of the Object Oriented Version? It doesn't seem obvious ... yet.

Activity 2 Thinking objectively

The other programming paradigms are all well and good, but they don't seem to naturally model the real world. Object Oriented Programming, however, is designed to do just that. The main difference between imperative / structural programming and object oriented programming is that, in structural programming, the lines of code and the data on which they operate are stored separately. An object oriented program puts the data and the processes that can be carried out on that data in one place. We can also place restrictions on how the data can be manipulated by the code.

Think about it, the world is made from ...


The following video is quite old but still gives the right messages about Object Oriented Programming (and explains lots of the key terms). There is a particularly funny bit at 7:50s ...

Beginner Developer Learning Center

During the AS Course, we studied a topic called 'How to solve it, better'. In this we discussed basic concepts of Object Oriented Design - Information hiding, encapsulation and interfaces.

Task 2.1

Visit How to solve it, better and find the section on Information hiding, encapsulation and interfaces. Write three quick definitions in your books, one for each of these three concepts.

OUTCOME : Three definitions for information hiding, encapsulation and interface.

Objects are defined by their class. Objects encapsulate the properties and methods of the class. It's the properties and methods that make objects in the class similar. The values of the properties describe the differences between each instance of an object.

Task 2.2
 Pet Caretaker

As a learning exercise, it's always a good idea to look at a real example. In this script, we will create a virtual pet of the Tamagotchi style.

Download a copy of the class

Download the petCaretaker class definition and execute it in IDLE. Your teacher will provide you with a printed copy of it and take you through the script and explain how it works.

During the demonstration

You should follow the examples your teacher shows you. Write notes on the printout of the class to describe it's operation if you need to.

the demonstration

You should write notes to explain the meaning of the following features of OOP ...
  • Instantiating an object from a class definition
  • Class / static attributes and static methods
  • Constructors (__init__)
  • Attributes / properties
  • Accessor methods (ways of retrieving and modifying attributes)
  • Private / Public attributes and methods
  • Ways of protecting the class / ensuring integrity / encapsulation
  • An 'interface' and what it's used for
OUTCOME : An annotated script for the petCaretaker.py class and a set of notes explaining key ideas.

Inheritance and Polymorphism

The power of OOP comes from the fact that we can define one class and base other classes on it using the concepts of inheritance and polymorphism.

Inheritance describes the way in which a subclass takes on (or inherits) the properties and methods of its parent class. We can use an inheritance diagram to represent this relationship. The inheritance diagram shows the name of the class, its properties, it's methods and it's relationship to other classes in the hierarchy. Notice the open arrows ...

The following simplified inheritance diagram shows the relationship between abstract classes (animal, reptile, mammal and feline) and concrete classes (lion, tiger, bear, snake). It is not usual to create (or instantiate) objects from abstract classes since we would never, for instance, see a generic reptile wondering around, would we?

The arrow should be read as an 'is a' relationship. For instance ...

"The Bear is a Mammal"

Click to enlarge

[need up update to change arrows to open rather than closed]

Each time your create a new class which inherits from another, it should become a more specific example of that object. Inheritance shouldn't add complexity.

Polymorphism (literally, 'taking on many shapes') describes the way in which the same method is implemented differently in different subclasses. For instance, all animals makeNoise() but the implementation of makeNoise() can vary between the lion, tiger and bear. Implementing a method defined in a parent differently in its subclasses is called overriding. Sometimes, however, it doesn't make sense to define methods in abstract classes, but in the example below, I have done just to show you how overriding works.

Task 2.3

Examine the abstract shapes class and create some squares

Open the shapesClass file using IDLE (right click and choose 'edit with IDLE'). Inspect the script and compare it to the inheritance diagram I have given below ...

Click enlarge

In the class diagram In Python 
Protected attributes and methods are prefixed with a hash sign (#)  Protected attributes and methods are prefixed with a single underscore (_
Private attributes and methods are prefixed with a minus sign (-) Private attributes and methods are prefixed with a double underscore (__
Public attributes and methods are prefixed with a plus sign (+) Public attributes and methods are not prefixed with anything at all! 
Static attributes and methods are underlined  Static attributes are included in the parent class outside the __init__ method. Static methods are preceded by the @staticmethod decorator. 
Abstract methods are italicised. Abstract methods need to be declared as such using the @abstractmethod decorator and should raise a NotImplementedError
Each attribute shows its type There is no strict typing in Python so no need for this. 
Each method shows the parameters with their type and, if relevant, a return type as well. Again, as there is no strict typing in Python, there is no need to declare this. 

Execute the script using 'Run > Run Module' or press F5. The console window will appear and you will be given a new prompt. Type the following commands, pressing the  Enter  key after each one.

>>> myShape = shape("Blue")
>>> mySquare = square("Red",4)
>>> yourSquare = square("Green",6)
>>> mySquare.getColour()
>>> yourSquare.getColour()
>>> mySquare.setColour("Yellow")
>>> mySquare.getColour()
>>> yourSquare.getColour()

First, we try to instantiate an abstract shape object but we can't because it contains abstract methods (see below). Next we instantiate two objects called mySquare and yourSquare using the square(shape) subclass. The square(shape) class inherits both the private __colour property and the getColour() and setColour() methods from it's parent class, shape(). We then use those methods to query, change and requery the colour of mySquare() whilst making sure that the related property in yourSquare() remains unchanged.

Create a circle and compare it's behaviour to that of a square

Now we'll create a circle using the circle(shape) class and investigate the polymorphic behaviour of the getArea() and getPerimeter() functions of the square(shape) and circle(shape) class. Type the following commands, pressing the  Enter  key after each one.

>>> myCircle = circle("Blue",4)
>>> mySquare.getArea()
>>> myCircle.getArea()
>>> mySquare.getPerimeter()
>>> myCircle.getPerimeter()

You should notice that even though we created our square and our circle with the same value for the side and the radius, the getArea() and getPerimeter() functions behave differently. This is called polymorphism

Implement your own triangle subclass

Now try to implement a new subclass called triangle(shape) and test it's operation. Document what you have done and print out your amended script to put in your notebooks.

Draw an inheritance diagram

Draw yourself an inheritance diagram including properties and methods to show the relationship between the different classes in your geometric world. Use the example above to help you.

OUTCOME : Documentation related to testing the development and operation of a new subclass, triangle and a lovely inheritance diagram.

Abstract, virtual and static methods

We've already seen an example of a static method in the petcaretaker.py script. Prefixing the method with the @staticmethod decorator allows it to be invoked without the instantiation of any objects of that class or subclass. They are often used to keep track of class wide attributes. I also used a static method in the shapes class to keep track of how many circles and squares had been instantiated from its subclasses.

The .getArea() method in the shapes class is known as a virtual method since it is defined in the parent class (albeit, just to provide an interface; an empty method) but can be overriden in the subclasses.

An abstract method is a method defined in a base class that may not provide any implementation but must be overriden in its subclasses. There is no built in way of declaring abstract methods directly in Python without using the Abstract Base Class (abc) module.

from abc import ABCMeta, abstractmethod

class abstract(object,metaclass=ABCMeta):
    def cannotCallMe(self):
        raise NotImplementedError

Well, you might ...

Task 2.4
 Your own example
shapes.py class as inspiration

Use the shapes.py class that we have already met, try to come up with your own example which includes ...
  • Inheritance
  • Polymorphism
  • Abstract, virtual and static methods
If you can't come up with your own idea, try to implement the animals class (and it's associated subclasses).

OUTCOME : Class definitions of your own, including examples of inheritance, polymorphism, abstract, virtual and static methods. 


So far, we've only looked at examples where subclasses are defined by their parent classes. Sometimes, objects can associated with other objects. There are two situations ...
  • Composition association where one class belongs in a collection. This is an 'owns' relationship where the part cannot exist without the whole. If the whole is destroyed, so are its parts.
  • Aggregation association where one class belongs in a collection but does not depend on the whole for it's existence. This is a 'has' relationship.
For instance, a vehicle is composed of an engine, seats and wheels. When the vehicle is destroyed, so are the engine, seats and wheels. However, a car (which is a type of vehicle) can have an occupant (a driver or a passenger) who, hopefully, is not destroyed if the car is.

Click to enlarge

This diagram is based on UML (Unified Modelling Language) conventions, shown in moderate completeness below ...

Click to enlarge

Task 2.5
Web browser

The vehicle example is a simple, and quite common one. Visit the following website and read about an example involving chairs. Make some notes, maybe draw a diagram, which explains how this example describes the two different types of association.

OUTCOME : Notes and / or diagram involving chairs and their association.

OOP Design Principles

You are only just beginning on a long journey into the mastery of OOP, but there are some key principles to keep you going.
  1. Encapsulate what varies
  2. Favour composition over inheritance
  3. Program to interfaces, not implementation

Task 2.6
 Read a book.
Web browser
Lack of integrity

There is so much reading material out there that it's difficult to know where to start. One of the most famous names in the field of object oriented design is Grady Booch - he was partly responsible for developing UML. One of his most well known books is called 'Object Oriented Analysis and Design with Applications'. A quick Google search will turn up some interesting results. Buy it from Amazon, obviously.

OUTCOME : Nothing really - just some reading if you want to learn more.

Extension Activities 

How about these extra activities to whet your appetite further?
  • There is a great book called 'Learn You a Haskell for a Great Good' which is brilliant and great fun. You might want to grab yourself a copy or read it online for free. "Holy Sh*t!"

  • Fancy learning more OOP languages? Start with the following list of resources ...

    Greenfoot : Teaches object oriented programming graphically using actors which live in worlds.
    BlueJ : Very similar to Greenfoot but textual based rather than graphical.
    Java : The 'classic' oop language.

    If you need any help getting the software, have a word with me and I'll point you in the right direction.

  • A challenging programming exercise might be to write a program of the game Hangman, using objects. The computer thinks of a word, and the user has to guess what it is, by suggesting a letter. For each letter that is wrong, an additional part of the gallows is added to the display. When the user guesses the computer’s word correctly, they have won. When the complete gallows have been built, and the user has not yet guessed the word, the user has lost.

  • There is a great tutorial on OOP in Python at Python Course.

  • Some great notes on OOP design principles.

  • Full list of Python magic methods.

What's next?

Before you hand your book in for checking, make sure you have completed all the work required and that your book is tidy and organised. Your book will be checked to make sure it is complete and you will be given a spicy grade for effort.