Programming technique · B3.1.2, B3.1.4
Classes and objects
A class describes a type. Each object created from that class has its own identity and instance state while following the same initialisation and method definitions.
What you need to be able to do
Design
Turn requirements into a class name, attributes, methods and a UML class diagram.
Construct
Write a class, establish starting state and create objects from it.
Trace
Explain which object receives a method call and prove that separate objects keep independent state.
Start from requirements: a library book
A library needs to represent many books. Each book has a title, author and loan state. A book can be borrowed, returned and described.
Class
LibraryBook represents the repeated entity.
Attributes
title, author and a borrowed/available value describe one book's state.
Methods
borrow(), returnBook()/return_book() and summary() describe useful behaviour.
+ title: String+ author: String+ borrowed: boolean + LibraryBook(title: String, author: String)+ borrow(): void+ returnBook(): void+ summary(): String + title: str+ author: str+ borrowed: bool + __init__(title, author)+ borrow()+ return_book()+ summary(): str Design before coding
UML is a compact plan. It lets you decide what belongs to the class before syntax distracts you.
+ name: String+ score: int + Player(name: String, score: int)+ addPoints(points: int): void+ summary(): String + name: str+ score: int + __init__(name, score)+ add_points(points)+ summary(): str Read the design before the code
Answer each question before opening the model answer.
-
If the requirement says “a player has a name and score”, where should those appear in the UML?
Reveal model answer
As attributes/fields in the middle section of the class box.
-
If the requirement says “a player can add points”, where should that appear?
Reveal model answer
As a method/operation, because it is behaviour.
-
Why plan two example LibraryBook objects before coding?
Reveal model answer
It checks that the class design can represent different concrete states and helps expose attributes or methods that do not really belong.
Define one class
Instance state
Named values stored by each object, such as name or score.
Constructor
A constructor has the class name and establishes a new object's starting state when new creates it.
__init__
Python calls __init__ after creating the object so the method can establish its starting attributes.
Instance method
Behaviour defined once by the class but executed for a particular receiving object.
Starting state can come from parameters or sensible defaults
Not every instance attribute must be supplied by the caller. The important question is what state a new object should have.
| LibraryBook value | How it could start | Reason |
|---|---|---|
| title | supplied when the object is created | Different books need different titles. |
| author | supplied when the object is created | Different books may have different authors. |
| borrowed | false/False inside initialisation | A newly added book can begin available without asking the caller to repeat that value. |
The receiving object matters
| Idea | Java | Python |
|---|---|---|
| Create an object | new Player("Ari", 10) | Player("Ari", 10) |
| Current/receiving object inside an instance method | this | self |
| Call behaviour on Ari | ari.addPoints(5) | ari.add_points(5) |
When ari.addPoints(5) runs, Ari is the receiving object. A field written as this.score means the score belonging to that receiver.
When ari.add_points(5) runs, Python passes Ari into the method as self. Therefore self.score is Ari's score for that call.
Create independent objects
namescore initialiseadd pointssummary ari
- name
- "Ari"
- score
- 10 → 15
sam
- name
- "Sam"
- score
- 20
Trace construction and method calls
| Statement | Created object or receiver | Ari state | Sam state |
|---|---|---|---|
new Player("Ari", 10) | new object assigned to ari | Ari, 10 | — |
new Player("Sam", 20) | new object assigned to sam | Ari, 10 | Sam, 20 |
ari.addPoints(5) | ari | Ari, 15 | Sam, 20 |
| Statement | Created object or receiver | Ari state | Sam state |
|---|---|---|---|
Player("Ari", 10) | object assigned to ari | Ari, 10 | — |
Player("Sam", 20) | object assigned to sam | Ari, 10 | Sam, 20 |
ari.add_points(5) | ari becomes self | Ari, 15 | Sam, 20 |
Predict object state
Answer each question before opening the model answer.
-
Ari starts at score 10 and Sam at score 20. After only Ari receives add points 5, what are the two scores?
Reveal model answer
Ari is 15 and Sam remains 20. Separate objects keep separate instance state.
-
Does defining addPoints/add_points once mean every object changes whenever the method is called?
Reveal model answer
No. The class defines the behaviour once, but the call has a particular receiver. Only that object's instance state is changed unless the code deliberately reaches shared state.
-
What is the difference between the Player class and the variable ari?
Reveal model answer
Player is the reusable type/class definition. ari refers to one particular Player object created from that class.
Keep the class separate from the program that uses it
This is a useful classroom and professional organisation habit: class code describes the model; a separate runner creates objects and tests behaviour.
Java
Place a public LibraryBook class in LibraryBook.java and the program entry point in a separate file such as LibraryApp.java. Public top-level class names normally match their filenames.
Python
Place LibraryBook in library_book.py, then use from library_book import LibraryBook in main.py.
Why bother?
Tests and runner code can change without turning the model class into one large mixed-responsibility file.
Common mistakes to catch
Class is not object
The class is the reusable type definition. Ari and Sam are separate objects created from it.
this means this object
Inside the class, this.name identifies the field belonging to the receiving object.
self is the receiver
Python passes the receiving object into the method as self.
Caller prints returned text
summary() returns a value; the caller decides whether and where to display it.
Design, then build
Choose a challenge only after you can identify its class, attributes, methods and starting state. Sketch the UML, then complete the required handwritten pseudocode before coding.
Challenges Choose one
Choose a challenge that feels appropriate for you. Code heat is only a rough estimate, not a fixed level.
Student Object
SelectedDesign and construct a Student class with name and grade fields, a constructor, an improveGrade method and a returning summary method. Create two objects with different starting values, change only one student and prove that the second object's state remains unchanged. Include a small UML class diagram before coding.
Bank Account
SelectedDesign and construct a BankAccount class with holder and balance fields, a constructor, deposit and withdraw methods, and a returning summary method. Instantiate at least two accounts and demonstrate that method calls affect only the receiving object. Detailed private-state rules are introduced in encapsulation, so keep this first model transparent and focused on object construction.
Dice Class
SelectedDesign and construct a Dice class with sides and currentValue fields. The constructor sets the number of sides, roll generates and stores a valid random value, and summary returns the object's current state. Create dice with different numbers of sides and test that each keeps independent state.
Virtual Pet
SelectedDesign and construct a Pet class with name, hunger and happiness fields. Add a constructor, feed and play methods, and a returning summary method. Create two pets with different starting state, call different methods on them and trace which object receives each call. Include UML that matches the completed class.
Selected challenge
This choice is shared with the portfolio setup page.
Plan your solution in handwritten pseudocode
Before opening your IDE or writing any program code, handwrite pseudocode for this challenge on paper.
Not marked complete. If you submit now, the GitHub README will record “No”.
Create your challenge folder
Run this command after planning. It creates the correct empty folder inside your portfolio.
Complete the challenge
Use your handwritten pseudocode as the starting plan, then write and test your solution in the folder created above.
Optional two-level scaffold
Try from your handwritten pseudocode first. Scaffold gives some structure; Scaffold + comments gives stronger guidance. Use only the level you need, and update your pseudocode first if the support changes your plan.
Submit for review
Run this when your program is complete. It creates the README, commits the folder and pushes it. The README records whether you marked the handwritten pseudocode as complete; the paper itself is handed to your teacher separately.