Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

OS 4.1 (2 of 6): Object-oriented design

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

50 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A game with 100 enemies

You make a game. It has 100 zombies. Each zombie has a name, some health and a way to attack.

Do you write the same code 100 times? No. You write a plan once. Then you make 100 copies from the plan.

This is the big idea of object-oriented design. Object-oriented means you build a program from objects.

Key words

WordWhat it meansExample
ClassA plan for making objects. It says what they know and what they can do.Character
ObjectOne thing made from a class. Also called an instance.Sam, a Character
MethodA small named job that belongs to a class.take_damage()
AttributeA value that belongs to an object.health
EncapsulationKeeping data and its code together, and protecting the data.
Data abstractionShowing only what the user needs, and hiding the rest.
InheritanceA new class takes everything from an old class, then adds or changes things.
PolymorphismDifferent objects answer the same method call in their own way.
Design patternA tested answer to a problem that comes up again and again.

The cells students fill in are left blank in this preview.

A class is a plan

A class is like the plan for a house. You can build many houses from one plan.

Each house is an object. Each object has its own attributes, such as a name and health. Each object can do things. These things are methods.

An object made from a class is also called an instance.

One class makes two objects

Code: python
class Character:
    def __init__(self, name, health):
        self.name = name
        self.health = health

    def speak(self):
        return self.name + " says: Hello"


sam = Character("Sam", 10)
ben = Character("Ben", 7)
print(sam.speak())
print(ben.health)

# Make a third Character and print what it says.

Make a free account to save your work and track your progress.

Check: class or object?

Have a go

Check: class or object?

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The four characteristics

IdeaIn simple wordsReal life
EncapsulationData and its methods live together. Outside code cannot break the data.A bank machine: you press buttons, you cannot reach the cash
Data abstractionShow the simple view. Hide the details.A car pedal: you press it, you do not see the engine
InheritanceA child class gets everything from its parent class.A Zombie is a Character with a different voice
PolymorphismSame call, different result for each type.Say "make a sound" to a cat and a dog

The cells students fill in are left blank in this preview.

Encapsulation protects the health

Code: python
class Character:
    def __init__(self, health):
        self._health = health   # the _ means: keep out

    def take_damage(self, amount):
        self._health = max(0, self._health - amount)

    def health(self):
        return self._health


c = Character(10)
c.take_damage(50)
print(c.health())   # 0, never below 0

Make a free account to save your work and track your progress.

One call, a different answer for each class

Code: python
class Animal:
    def speak(self):
        return "..."


class Cat(Animal):
    def speak(self):
        return "Meow"


class Dog(Animal):
    def speak(self):
        return "Woof"


for pet in [Animal(), Cat(), Dog()]:
    print(pet.speak())

Make a free account to save your work and track your progress.

A UML class diagram

classDiagram
  class Character {
    +name
    +health
    +take_damage(amount)
    +speak()
  }
  class Zombie {
    +speak()
  }
  class Player {
    +score
    +add_score(points)
  }
  Character <|-- Zombie
  Character <|-- Player

Match the idea

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Design patterns

Many developers meet the same problems. Over time, they found good answers. These answers have names. We call them design patterns.

There are three groups. Creational patterns help you make objects. Structural patterns help you put objects together. Behavioural patterns help objects work with each other.

Common patterns

GroupPatternWhat it doesExample
CreationalSingletonOnly one object of a class may existOne settings object for the whole app
CreationalFactoryA method makes the right object for youAsk for "pizza" or "burger" and get the right order
StructuralAdapterMakes two parts that do not fit work togetherA plug adapter for travel
StructuralFacadeOne simple front for a complex systemA single "Pay" button hides many steps
BehaviouralObserverWhen one object changes, the others are toldA match score app sends goals to every fan
BehaviouralStrategySwap one way of doing a job for anotherChoose the fastest or the cheapest route

The cells students fill in are left blank in this preview.

Build the Character and Zombie classes

Finish the Character class. It keeps a name and health. take_damage lowers the health, but never below 0. is_alive says if health is above 0. speak gives back text. Then finish Zombie. A Zombie is a Character, but it says Grr. Press Run Tests.

Code: python
class Character:
    def __init__(self, name, health):
        # Keep the name and the health on the object.
        pass

    def take_damage(self, amount):
        # Take amount off the health. Health never goes below 0.
        pass

    def is_alive(self):
        # True while health is above 0.
        pass

    def speak(self):
        # Give back text like: Sam says: Hello
        pass


class Zombie(Character):
    # A Zombie is a Character. It only changes speak.
    # Its speak gives back text like: Ben says: Grr
    pass

Make a free account to save your work, or press Start lab to work through the whole lesson.

Which pattern fits?

Have a go

Which pattern fits?

6 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Exit quiz

Have a go

Exit quiz

6 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.