Design a class by identifying what its objects must represent, storing their state in attributes, and defining their behaviour through methods. Each method should have one clear purpose, appropriate parameters, and a return value when it must produce a result.
For B3.1, begin with the problem requirements. A class is a blueprint, while an object is an instance of that class. Choose only the attributes and operations needed for the class's responsibility.
| Design element | Question to ask | Example for BankAccount |
|---|---|---|
| Attributes | What data describes each object? | accountHolder, balance |
| Constructor | What initial values are required? | Set the holder and opening balance |
| Methods | What operations must the object perform? | deposit, withdraw, getBalance |
| Parameters | What information must an operation receive? | amount for deposit(amount) |
| Return value | What result should an operation provide? | getBalance() returns the balance |
A possible design is:
CLASS BankAccount
PRIVATE accountHolder
PRIVATE balance
CONSTRUCTOR(holder, openingBalance)
accountHolder = holder
balance = openingBalance
END CONSTRUCTOR
METHOD deposit(amount)
IF amount > 0 THEN
balance = balance + amount
END IF
END METHOD
METHOD getBalance()
RETURN balance
END METHOD
END CLASS
Declaring attributes as private supports encapsulation: the object's state is controlled through its methods rather than changed directly by external code. Validation belongs inside the relevant method; for example, deposit rejects non-positive amounts. A withdraw method should similarly check that the amount is positive and does not exceed the available balance.
A common misconception is that every method must return a value. A mutator such as deposit may only change object state, whereas an accessor such as getBalance returns information without changing it.
In an IB exam, identify the required attributes before writing methods. Show the constructor, parameters, state changes, validation, and return values clearly; do not merely list method names without explaining their behaviour.