Code Companion
Java

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.

IB DP CS standards B3.1.2 and B3.1.4: Construct class designs using UML, define classes, establish starting state and instantiate objects.

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.

LibraryBook
+ title: String+ author: String+ borrowed: boolean
+ LibraryBook(title: String, author: String)+ borrow(): void+ returnBook(): void+ summary(): String
At this stage the UML is focused on class design. Controlled private state is introduced later in encapsulation.
LibraryBook
+ title: str+ author: str+ borrowed: bool
+ __init__(title, author)+ borrow()+ return_book()+ summary(): str
At this stage the UML is focused on class design. Controlled internal state is introduced later in encapsulation.

Design before coding

UML is a compact plan. It lets you decide what belongs to the class before syntax distracts you.

Player
+ name: String+ score: int
+ Player(name: String, score: int)+ addPoints(points: int): void+ summary(): String
The class name, fields and operations correspond directly to the requirements.
classLibraryMember
classLibraryBook
Association: a plain line between class boxes shows that objects of the classes are related or interact. The line alone does not mean inheritance and does not claim strong ownership or lifetime dependence.
Player
+ name: str+ score: int
+ __init__(name, score)+ add_points(points)+ summary(): str
The UML describes the same responsibilities even though Python does not declare these types in the class syntax shown.
classLibraryMember
classLibraryBook
Association: a plain line between class boxes shows that objects of the classes are related or interact. The line alone does not mean inheritance and does not claim strong ownership or lifetime dependence.

Read the design before the code

Answer each question before opening the model answer.

  1. 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.

  2. If the requirement says “a player can add points”, where should that appear?

    Reveal model answer

    As a method/operation, because it is behaviour.

  3. 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 valueHow it could startReason
titlesupplied when the object is createdDifferent books need different titles.
authorsupplied when the object is createdDifferent books may have different authors.
borrowedfalse/False inside initialisationA newly added book can begin available without asking the caller to repeat that value.
Python option: default parameter values can make some constructor inputs optional. Use them when a genuine default makes the interface clearer; do not add defaults merely to avoid thinking about required state.
Java option: overloaded constructors can provide more than one valid construction path. Keep each path responsible for establishing a complete valid starting state.

The receiving object matters

IdeaJavaPython
Create an objectnew Player("Ari", 10)Player("Ari", 10)
Current/receiving object inside an instance methodthisself
Call behaviour on Ariari.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

Player class
namescore
initialiseadd pointssummary

ari

name
"Ari"
score
10 → 15

sam

name
"Sam"
score
20
The method is defined once, but ari.addPoints(5) changes Ari because ari is the receiver. Sam's state is independent.
The method is defined once, but ari.add_points(5) changes Ari because ari becomes self. Sam's state is independent.

Trace construction and method calls

StatementCreated object or receiverAri stateSam state
new Player("Ari", 10)new object assigned to ariAri, 10
new Player("Sam", 20)new object assigned to samAri, 10Sam, 20
ari.addPoints(5)ariAri, 15Sam, 20
StatementCreated object or receiverAri stateSam state
Player("Ari", 10)object assigned to ariAri, 10
Player("Sam", 20)object assigned to samAri, 10Sam, 20
ari.add_points(5)ari becomes selfAri, 15Sam, 20

Predict object state

Answer each question before opening the model answer.

  1. 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.

  2. 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.

  3. 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

Challenge ID: PC-T19-C01 · Standards: B3.1.2, B3.1.4

Design 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.

Scaffold available
A Student class blueprint connected to several student objects with independent values.

Bank Account

Challenge ID: PC-T19-C02 · Standards: B3.1.2, B3.1.4

Design 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.

Scaffold available
A BankAccount object with holder, balance, deposit and withdraw responsibilities.

Dice Class

Challenge ID: PC-T19-C03 · Standards: B3.1.2, B3.1.4

Design 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.

Scaffold available
A Dice class blueprint creating dice objects with their own current values.

Virtual Pet

Challenge ID: PC-T19-C04 · Standards: B3.1.2, B3.1.4

Design 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.

Scaffold available
A virtual Pet object with name, hunger, happiness, feed and play responsibilities.