B3.1 · Book pp. 394–416
Fundamentals of OOP for a single class
So far, your data types have been integers, strings and lists. With object-oriented programming, you can invent your own, such as Student, Book or BankAccount.
What you need to know
- B3.1.1 Evaluate the fundamentals of OOP.
- B3.1.2 Construct a design of classes, their methods and behaviour.
- B3.1.3 Distinguish between static and non-static variables and methods.
- B3.1.4 Construct code to define classes and instantiate objects.
- B3.1.5 Explain and apply encapsulation and information hiding.
A class is a blueprint. An object is one house built from it. Every house has the same plan, but its own paint and its own owner.
⚠️ Common mistake
It is easy to carry on thinking in steps. Begin by asking what things exist in the problem, what each one knows, and what each one can do.
B3.1.1 Why OOP?
Functions standardize behaviour. OOP also standardizes the structure of data, by keeping data and the methods that act on it together.
| Advantages | Disadvantages |
|---|---|
| Modularity: objects can be built and changed separately | Learning curve: the ideas take time |
| Reuse: a class can be imported into other projects | Complexity: small problems become heavier than they need to be |
| Encapsulation: data is changed only through methods | Overuse: not everything is naturally an object |
| Scale and teamwork: classes can be shared out | Overhead: extra time and memory, which matters where speed is critical |
Would you use OOP to convert one temperature?
No. A single function is enough, as a class would add complexity for no benefit. OOP pays off when many related things hold state, as in a library system or a game.
B3.1.2 UML class diagrams
A UML class diagram is a language-independent design for a class, with three rows.
| BankAccount | Row 1: class name |
− name: String− balance: double | Row 2: variables and types |
+ BankAccount(String)+ deposit(double): void+ withdraw(double): void+ transfer(double, BankAccount): void | Row 3: methods, parameters and return types |
+ means public and − means private. You should be able to draw a diagram from code, and write code from a diagram.
Try it: draw a class diagram for a Book
Book, then − title: String, − borrowed: boolean, then + Book(String), + borrow(): void, + giveBack(): void and + isBorrowed(): boolean.
B3.1.4 Coding classes and instantiating objects
Instantiation creates an object. Memory is allocated, then the constructor initializes the instance variables.
- Python: the constructor is __init__. Inside the class, self means this object, and it is the first parameter of every instance method.
- Java: the constructor has the class’s name, and new creates the object. this means this object, and is optional unless a name is ambiguous.
Lists can hold objects too, but each element still needs creating.
| Name | Style | Example |
|---|---|---|
| Class | Capitalized singular noun | BankAccount |
| Method | A verb | calculateTotal, calculate_total |
| Array of objects | Plural | accounts |
✏️ Book corrections
- Under “Creating an object”, the book’s text says “Creating an array”. It means creating an object.
- It says the constructor “technically” returns the initialized object. In Python, __init__ returns None: the object already exists, and __init__ only fills it in.
B3.1.5 Encapsulation and information hiding
Encapsulation bundles data with the methods that use it. Information hiding stops outside code from reaching the data directly. Together they protect values, and let you change a class’s internals without breaking the code that uses it.
| Java keyword | UML | Visible to | Python |
|---|---|---|---|
private | − | Only code inside the class | __name or _name |
protected | # | The class and classes that inherit it | Convention only |
public | + | Any code | name |
default (no keyword) | Code in the same package | No equivalent |
Python only has conventions. A double underscore renames the variable, to _BankAccount__balance, which makes accidents unlikely but does not stop a determined programmer. For this course, treat it as private.
An accessor (getter) returns a private value. A mutator (setter) updates one, and can reject bad values.
The final line fails on purpose, which shows the variable is hidden.
✏️ Book correction
The book says private means accessible by the “current object”. In Java, private is per class: one BankAccount’s method can read another BankAccount’s private balance. Java’s protected also allows access from the same package.
B3.1.3 Static and non-static
| Static | Non-static | |
|---|---|---|
| Belongs to | The class | Each object |
| Copies | One, shared | One per object |
| Needs an object? | No | Yes |
| Called with | BankAccount.find(…) | amy.deposit(…) |
| Good for | Interest rate, next ID number | Name, balance |
✏️ Book corrections
- The book says no static method may access instance variables. It cannot do so directly, with no object. Given an object as a parameter, it can, which is just what find() does with each account.
- Its Java CollectionOfThings keeps the item count in a static variable, and resets it in the constructor. So creating a second collection wipes the count of the first. Each collection needs its own count, so this must be non-static.
- Its remove() never finds the last item, as the loop stops one short.
- Its Java find() loops over an array of 10 that holds only 3 accounts, so searching for a missing name hits null and throws a NullPointerException. Test for null first.
Objects inside objects
Here, each Student holds a list of Assessment objects.
✍️ Try it: a library
Finish give_back, add more books, then add a static method that counts how many are out on loan.
Quick quiz
Exam-style questions
These are written for this site in the style of Paper 2. Answer on paper first, then open the mark points.
-
Distinguish between a class and an object. [2]
Mark points
- A class is a template that defines variables and methods [1].
- An object is one instance created from it, with its own values [1].
-
Outline two advantages and two disadvantages of OOP for a large school records system. [4]
Mark points
- Modular classes can be given to separate programmers [1].
- Classes such as Student can be reused [1].
- It takes more design and learning time [1].
- It has extra overhead in time and memory [1].
-
Explain why a static method cannot directly access instance variables. [3]
Mark points
- A static method belongs to the class [1].
- It can run when no object exists [1].
- So there is no object whose variables could be used [1].
-
Explain how private variables with accessors and mutators protect data. [3]
Mark points
- Outside code cannot change the variable directly [1].
- A mutator can check a value before accepting it [1].
- So the internal design can change without breaking other code [1].
-
Construct a class Ticket with a private price, a constructor, an accessor, and a method discount(percent) that reduces the price. [5]
Mark points
- Class header and private variable [1].
- Constructor sets price from a parameter [1].
- getPrice returns price [1].
- discount takes one parameter [1].
- price is reduced by price × percent ÷ 100 [1].
-
A class Room needs a count of all rooms created. Outline how to do this. [3]
Mark points
- Add a static integer starting at 0 [1].
- Add 1 to it in the constructor [1].
- Provide a static accessor to return it [1].