Programming principles and design · Lesson 31 of 60 · Code lesson, JavaScript or Python · Optional
Object-oriented programming
A class is a blueprint, and an object is one thing built from it, with its own data and behaviour.
Inheritance lets a class reuse another class's code, composition builds a class by holding other objects, and polymorphism lets different classes answer the same method call in their own way.
Use inheritance when something truly is a kind of something, and composition when it has something.
Worked example
In JavaScript, class Dog extends Animal inherits from Animal, and a method with the same name overrides it.
class Animal {
speak() {
return "...";
}
}
class Dog extends Animal {
speak() {
return "Woof";
}
}
console.log(new Dog().speak());Output: Woof
In Python, class Dog(Animal) inherits from Animal, and a method with the same name overrides it.
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
print(Dog().speak())Output: Woof
Your turn
The program reads animal kinds and asks each one to speak. Cat does not have its own speak yet, so it prints ... Give Cat a speak method that returns Meow.
Your program is checked with these 3 inputs:
Input:
dog cat
Expected output:
Woof Meow
Input:
cat
Expected output:
Meow
Input:
dog dog
Expected output:
Woof Woof
Loading your practice…
Preparing your workspace…