Computer Science › Section G · Programming languages › Topic G.5
Object-oriented programming
Most large programs written today, from phone apps to games, are organised as collections of objects that each look after their own data. Object-oriented programming is the set of ideas that makes that organisation work: classes, objects, encapsulation, inheritance and polymorphism.
Objects: data and behaviour together
In the imperative style, data sits in variables and separate functions work on it. Object-oriented programming (OOP) packages them together. An object holds its own data, stored in instance variables, also called attributes or fields, and carries methods, the functions that act on that data. Instead of a program sorting a list, the list is an object that is asked to sort itself. Each object is a self-contained unit with a clear job, so a large system can be built and understood as a set of cooperating parts. The ideas began with Simula in Norway in the 1960s and were developed further in Smalltalk at Xerox PARC in the 1970s.
Classes and instances
A class is the description from which objects are made: it declares which instance variables each object will have and defines the methods. An object built from a class is an instance of it. Many instances can come from one class, each with its own copy of the instance variables, just as many houses can be built from one plan, each with its own furniture. In Java, a declaration such as Counter a = new Counter(); creates an instance. In Python, a = Counter(0) does the same job. Calling a method uses dot notation, as in a.increment(), and inside the method Python refers to the current object as self.
Constructors
A newly made object needs sensible starting values. A constructor is a special method that runs automatically when an instance is created and sets up its instance variables. In Java and C#, a constructor has the same name as the class and no return type. In Python, the constructor is the method named __init__, and its first parameter, self, is the new object: def __init__(self, start): self.count = start. Arguments given when the object is created are passed to the constructor, so Counter(10) starts with count equal to 10. Without a constructor, every caller would have to remember to set up each object correctly.
Worked example: two independent objects
Python code: class Counter with __init__(self, start) setting self.count = start, and a method increment(self) doing self.count = self.count + 1. Then a = Counter(0), b = Counter(10), a.increment(), a.increment(), b.increment(), print(a.count, b.count). Steps: (1) Counter(0) runs the constructor, giving a its own count of 0. (2) Counter(10) gives b a separate count of 10. (3) The two calls on a raise a.count to 1 then 2; b is not affected. (4) The call on b raises b.count to 11. (5) Output: 2 11. Each instance keeps its own state, even though both share the same method code.
Encapsulation
Encapsulation means restricting outside access to an object's internals, so other code must work through the object's methods. Java and C# mark members private, usable only inside the class, or public, part of the interface: private int count; hides the field, while public int getCount() exposes its value safely. The payoff is control. A Thermostat class whose set_target method accepts only 5 to 30 degrees can never be pushed to 45, because no outside code can write the target directly. Python does not enforce privacy; a leading underscore, as in _target, is a convention meaning "internal, do not touch", and a double underscore triggers name mangling, which hides the name but does not lock it.
Inheritance
Inheritance lets a new class be defined as an extension of an existing one. The new class, the subclass or child, automatically has the parent's instance variables and methods, and can add more or replace some. A StudentTicket class written as class StudentTicket(Ticket): reuses everything in Ticket and only redefines how the price is worked out. Replacing an inherited method with a new version is called overriding. In Python, super().__init__(...) runs the parent's constructor from inside the child's, so shared setup is written once. Inheritance should model an "is a" relationship: a student ticket is a ticket.
Polymorphism
Polymorphism means that the same method call can produce different behaviour depending on the class of the object receiving it. If Ticket, StudentTicket and GroupTicket each define price(), a loop can call t.price() on every ticket in a list without checking which kind each one is; each object runs its own version. The calling code stays simple, and adding a new kind of ticket later needs a new class, not edits to every loop. The decision about which method runs is made while the program executes, based on the actual object, which is called dynamic binding.
Worked example: inheritance and polymorphism
Ticket stores event and base and has price() returning base. StudentTicket(Ticket) overrides price() to return base * 0.8. GroupTicket(Ticket) adds people, calling super().__init__(event, base) first, and its price() returns base * people * 0.9. The list tickets holds Ticket("Play", 20), StudentTicket("Play", 20) and GroupTicket("Play", 20, 5). Steps: (1) The plain ticket uses Ticket's price: 20. (2) The student ticket uses its override: 20 × 0.8 = 16.0. (3) The group ticket: 20 × 5 × 0.9 = 90.0. (4) Summing t.price() over the list gives 126.0. (5) All three still have event, inherited from Ticket, and isinstance(tickets[1], Ticket) is True.
OOP in practice
Because each method is a short imperative routine, object-oriented languages keep all the traditional features: variables, types, loops and functions. C++ added classes to C; Java and C# followed with OOP at their centre; Python, Swift and many others support it alongside other styles. Well-designed classes can be collected into libraries and reused like off-the-shelf components, which is why graphical interfaces are built from button, window and menu objects. Software engineering, covered in the topic "Modularity: coupling and cohesion", builds on these ideas when it judges how well a design is divided into parts.
Common mistakes to avoid
Confusing a class with an object: the class is the description, and instances are the things that hold data. Forgetting self in a Python method's parameters or when using instance variables, so count becomes an unrelated local variable instead of self.count. Assuming Python's underscore makes a field truly private. Using inheritance where the "is a" test fails, such as making Car a subclass of Engine; a car has an engine, so it should hold one as an instance variable. Writing if-chains that test an object's class when polymorphism would let each class handle the call itself.
Key takeaways
Objects combine data, held in instance variables, with methods that act on it. A class describes its objects, and each instance has its own copies of the instance variables. Constructors initialise new objects: __init__ in Python, a method named after the class in Java and C#. Encapsulation restricts outside access so objects stay valid. Inheritance lets a subclass reuse and override a parent class's members. Polymorphism lets one method call behave appropriately for each object's class, decided at run time.
Flashcards
Flashcard
A unit holding its own data and the methods that act on it
Test your understanding
Question 1 of 5
Python: p = Counter(5); q = Counter(5); p.increment(); then print(p.count, q.count). With the Counter class from the reading, what is printed?
Question 2 of 5
What is the main purpose of a constructor?
Question 3 of 5
A Java class declares private double balance; and a public method deposit that rejects negative amounts. Which idea does this show?
Question 4 of 5
A loop calls s.area() on a list holding a Circle, a Square and a Triangle, and each computes its own area correctly. What is this called?
Question 5 of 5
Which design uses inheritance correctly?
