CIE AS & A Level Computer Science, section 20.1 (Programming paradigms)
The main terms
| Term | Meaning |
|---|---|
| Class | a template that defines the attributes and methods of a kind of object |
| Object | an instance of a class, with its own values |
| Attribute (property) | data held by an object |
| Method | a procedure or function that belongs to a class |
| Constructor | a method that creates an object and sets its starting values (NEW in pseudocode, __init__ in Python) |
| Getter | a method that returns an attribute |
| Setter | a method that changes an attribute (with a check) |
| Instance | one object made from a class |
Encapsulation
Encapsulation keeps the attributes private and only lets other code reach them through public methods. This protects the data (invalid values can be refused), and the inside can change without changing the code that uses the class.
- Private: only usable inside the class.
- Public: can be used from outside.
Inheritance
A child (derived) class takes the attributes and methods of a parent (base) class, and can add or change them. This reuses code.
Polymorphism and overriding
Polymorphism means the same method name can behave differently for different classes. When a child class redefines a parent's method, this is overriding. Overloading means a method name used with different parameters (Python does this with default arguments).
Containment (aggregation)
Containment is when a class has objects of another class as attributes (a "has-a" relationship), for example a Car contains an Engine. Inheritance is an "is-a" relationship: a Drum is an Instrument.
Example
class Instrument:
def __init__(self, name):
self.__name = name # private attribute
def get_name(self): # getter
return self.__name
def play(self):
return "..."
class Drum(Instrument): # inheritance
def play(self): # overriding
return "Boom"
band = [Instrument("Generic"), Drum("Snare")]
for i in band:
print(i.get_name(), i.play()) # polymorphism: Generic ... | Snare Boom
Benefits of OOP
Code is reused, easier to maintain, and models real-world things well.
Common mistake: confusing a class with an object. The class is the template; the object is one made from it. Also, inheritance is "is a", while containment is "has a".
Exam tip: use the exact terms and give an example for each. For encapsulation, state that attributes are private and accessed by methods.
Check yourself
What is the difference between a class and an object?
A class is a template, whereas an object is an instance created from it with its own values.
What is encapsulation?
Keeping data private within a class and accessing it only through public methods.
What is the relationship between a parent class and a child class called?
Inheritance.