Programming Polymorphism (OCR A Level Computer Science)
Revision Note
Written by: Robert Hampton
Reviewed by: James Woodhouse
Programming Polymorphism
To program polymorphism, you should already have a solid understanding of what polymorphism in Object Oriented Programming (OOP) is.
How do you Define Polymorphism?
Pseudocode
1. Create a blueprint for a general animal:
Define a template called
Animal
Give
Animal
a placeholder action calledspeak()
that does nothing yet
2. Create a blueprint for a dog:
Define a template called
Dog
based on theAnimal
templateOverride the
speak()
action forDog
to make it print "Woof"
3. Create a blueprint for a cat:
Define a template called
Cat
based on theAnimal
templateOverride the
speak()
action forCat
to make it print "Meow"
4. Create a function to make animals speak:
Define a function called
make_sound(animal)
Inside the function, tell the given
animal
to perform itsspeak()
action
5. Create a dog and a cat:
Build a
Dog
object and put it in a box labeled "dog"Build a
Cat
object and put it in a box labeled "cat"
6. Ask the dog and cat to speak:
Call the
make_sound()
function with thedog
objectCall the
make_sound()
function with thecat
object
Python
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Woof")
class Cat(Animal):
def speak(self):
print("Meow")
def make_sound(animal):
# calling the speak method of the Animal class
animal.speak()
dog = Dog()
cat = Cat()
make_sound(dog)
make_sound(cat)
Java
class Animal {
public void speak() {
// Empty default implementation
}
}
class Dog extends Animal {
@Override
public void speak() {
System.out.println("Woof");
}
}
class Cat extends Animal {
@Override
public void speak() {
System.out.println("Meow");
}
}
public class Main {
public static void makeSound(Animal animal) {
animal.speak();
}
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
makeSound(dog);
makeSound(cat);
}
}
Last updated:
You've read 0 of your 10 free revision notes
Unlock more, it's free!
Did this page help you?