Classes in Detail: Constructors, Static Members, UML and Program Structure
IB Computer Science · Option: Object-Oriented Programming and Databases
Reading and writing UML class diagrams. A class box has three compartments: the name, the attributes and the methods. A minus sign means private, a plus sign public; attributes are almost always private (encapsulation) and are reached through public getters and setters. An underlined member is static: it belongs to the class rather than to any object, so there is one copy shared by all instances — a counter of how many accounts have been created, or a constant such as the maximum overdraft. A static method can be called without an object and can only use static data. An arrow with a hollow triangle points from a subclass to its superclass and reads "is a": SavingsAccount is an Account. A plain line with multiplicities (1, 0..*) is association: a Customer has many Accounts. The exam gives a diagram and asks for code, or gives code and asks for the diagram; the mapping must be exact, including types and visibility.
Constructors. A constructor has the class's name and no return type, and runs once when an object is created, to put it into a valid starting state. It usually takes the values that cannot have sensible defaults (the account number) and sets the rest (balance starts at 0). A class may have several constructors with different parameter lists (overloading). A subclass constructor first calls the superclass constructor to set the inherited part, then sets its own attributes: SavingsAccount(number, rate) calls Account(number) and then stores rate. Objects created without going through the constructor — or with a constructor that forgets a field — are the source of many null-reference errors.
Overriding and calling the parent. A subclass may replace an inherited method with its own version of the same signature: SavingsAccount overrides withdraw to refuse going below zero, CurrentAccount overrides it to allow an overdraft. The version that runs is chosen by the object's actual class at run time — polymorphism — so a loop over an array of Account references calls the right withdraw for each element without testing its type. An override may call the parent's version to reuse the common part and add to it.
Program structure and good practice. Split code into classes by responsibility; keep each method short and doing one thing; name things for what they represent; use constants instead of magic numbers; keep data private and expose behaviour. Libraries provide tested classes (collections, dates, files) so that you do not rewrite them. The advantages examiners expect: reuse, easier maintenance because change is local, teams can work on separate classes, and code that models the problem so that it can be read by someone who knows the problem but not the code. The costs: more design effort up front, and performance overhead from layers of objects — which is why embedded systems often avoid heavy object-oriented designs.
Worked example: Example 1 — from a UML diagram to code, with a constructor and a static member
From the diagram in the figure, write the class Account with a static counter count that increases every time an account is created, and the class SavingsAccount with an overriding withdraw that refuses to withdraw more than the balance. Explain why count must be static and balance must be private.
Solution
Class Account.
class Account
private String number
private double balance
private static int count = 0
public Account(String number)
this.number = number
this.balance = 0
count = count + 1
end constructor
public void deposit(double amount)
if amount > 0 then balance = balance + amount
end method
public boolean withdraw(double amount)
balance = balance - amount
return true
end method
public double getBalance() return balance
public static int getCount() return count
end class
Class SavingsAccount.
class SavingsAccount extends Account
private double rate
public SavingsAccount(String number, double rate)
super(number)
this.rate = rate
end constructor
public boolean withdraw(double amount)
if amount > getBalance() then return false
return super.withdraw(amount)
end method
public void addInterest() deposit(getBalance() * rate)
end class
Why count is static. The number of accounts created is a property of the class, not of any particular account; if count were an ordinary attribute, each object would have its own copy and none of them would know the total. Static means a single copy, incremented in the constructor and read through a static method without needing an object.
Why balance is private. If it were public, outside code could set a negative balance or bypass the checks in withdraw; private forces every change to go through deposit and withdraw, where the rules are checked. A consequence you can see in the code: SavingsAccount is a subclass but still has to use getBalance and super.withdraw instead of touching balance directly — encapsulation applies to subclasses too.
Worked example: Example 2 — why polymorphism makes code shorter and safer when a new class is added
A bank has an array ACCOUNTS containing both SavingsAccount and CurrentAccount objects and needs to process all of them at the end of the month: add interest for savings, calculate overdraft fees for current accounts. There are two ways to write it: (A) check the type of each element and then call the corresponding method; (B) declare a method monthEnd() in Account, override it in each subclass, and call ACCOUNTS[I].monthEnd() in a loop. Compare them, then consider adding a class StudentAccount a year later.
Solution
Way A. loop I from 0 to N − 1: if ACCOUNTS[I] is SavingsAccount then addInterest, else if CurrentAccount then chargeOverdraft. It works correctly today, but the logic of which type of account does what sits at the place of the call, and every other place that has a similar loop — printing statements, calculating tax — repeats that chain of ifs.
Way B. Account declares monthEnd() (it may be empty or abstract); SavingsAccount overrides it to add interest; CurrentAccount overrides it to charge fees. The loop is reduced to just ACCOUNTS[I].monthEnd(), and the right version is chosen at run time according to the real class of the object. The logic for each type sits inside that class, exactly where a maintainer would look.
Adding StudentAccount a year later. With A, you must find every loop with an if chain throughout the program and add a branch; missing a single place is a silent bug — student accounts are skipped at month end and no one is told. With B, you write the new class with its own monthEnd(), and every existing loop handles it automatically without changing a single line. This is the real reason for polymorphism: not shorter code, but changes that are contained in the new class instead of scattered across the program.
The cost to mention. Way B requires design up front — deciding from the start that monthEnd() belongs to Account — and when reading the code, you cannot immediately see what happens at the line ACCOUNTS[I].monthEnd() but have to open each subclass. For a program with two account types that never change, way A is not wrong; polymorphism pays off as the system grows.
Common mistake
Trap 1 — writing a constructor with a return type or a name different from the class. A constructor has the same name as the class, has no return type, and a subclass calls the parent constructor first.Trap 2 — making the object counter an ordinary attribute. Each object gets its own copy; anything that belongs to the class must be static.
Trap 3 — a subclass touching the parent's private attribute directly. Encapsulation applies to subclasses too: use the parent's getters and methods.