AP Computer Science A · Class creation
Writing classes
1Anatomy of a class
A class defines the data (instance variables) and behaviour (methods) that every object of that type has.
public class BankAccount {
private String owner;
private double balance; public BankAccount(String name, double start) {
owner = name;
balance = start;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
balance += amount;
}
}
Every BankAccount object has its own copy of owner and balance.
Check yourself
Instance variables belong to:
Show the answer
Each individual object
Each object has its own copy.
2Encapsulation and access modifiers
Encapsulation means hiding an object's data and allowing access only through methods.
private: accessible only inside the class. Instance variables should be private.public: accessible from any class. Constructors and most methods are public.
Benefits: the class controls how its data changes (e.g. refusing a negative deposit), and its internal details can change without breaking code that uses it.
Accessing a private variable from another class, e.g. acct.balance = 100;, is a compile-time error.
A class diagram: private data, public constructor and methods
Check yourself
In AP CSA, instance variables should be declared:
Show the answer
private
Encapsulation.
3Methods and return values
A method header gives the access modifier, return type, name and parameters:
public boolean withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
return true;
}
return false;
}
- A non-void method must
returna value of its return type on every path. returnends the method immediately.- Preconditions describe what must be true before a method is called; postconditions describe what is true afterwards. These appear in comments in exam questions.
Check yourself
A method declared public int getCount() must:
Show the answer
Return an int on every path
Return type int.
4Objects as parameters and aliasing
When an object is passed to a method, the reference is copied, so the method can change the object's state through it.
Two variables referring to the same object are aliases:
BankAccount a = new BankAccount("Sam", 50);
BankAccount b = a;
b.deposit(20);
System.out.println(a.getBalance()); // 70.0
Only one object exists; both a and b point to it.
Check yourself
After BankAccount b = a; b.deposit(10); the balance of a:
Show the answer
Increases by 10
a and b are aliases.
5Going deeper: a complete class, design decisions and the exam's class-writing question
A class is a blueprint: it defines the state (instance variables) and behavior (methods) that each object of that type will have.
The parts, in the usual order
- Instance variables: declared private.
- Constructors: public; same name as the class; no return type.
- Methods: public if other classes should call them; private for internal helpers.
A complete example
public class BankAccount {
private String owner;
private double balance;
public BankAccount(String name, double startingBalance) {
owner = name;
balance = startingBalance;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
public String toString() {
return owner + ": " + balance;
}
}
Using it:
BankAccount acct = new BankAccount("Ada", 100.0);
acct.deposit(50.0);
boolean ok = acct.withdraw(500.0);
System.out.println(acct + " " + ok);
Output: Ada: 150.0 false. Printing an object calls its toString automatically.
Encapsulation: keeping data private and allowing access only through methods.
- The class can validate changes (no negative deposit; no overdraft).
- The internal representation can change without breaking code that uses the class.
acct.balance = -5;from another class does not compile.
Each object has its own copy of the instance variables. Two BankAccount objects have separate balances.
Design: from a description to a class
- Nouns that an object must remember become instance variables. Ask: does this value need to survive between method calls? If so, it is an instance variable; if it is needed only during one method, make it a local variable.
- Verbs become methods.
- Decide for each method: parameters (what it needs from outside), return type (what it gives back), and whether it changes the state.
Preconditions and postconditions: comments stating what must be true before a method is called and what it guarantees afterward. A method need not check its preconditions.
Private helper methods break up a long task and avoid repeated code; they are called from within the class without an object name.
toString: public String toString() returns a String describing the object. It should return the text, not print it.
equals: a class may define what it means for two of its objects to be equal:
public boolean equals(BankAccount other) {
return owner.equals(other.owner) && balance == other.balance;
}
A method can read the private variables of another object of the same class.
The class-writing free-response question: you are given a description and examples of use, and must write the whole class. A checklist:
public class Nameheader and braces.- Private instance variables for everything that must be remembered, including values that examples show changing between calls.
- A constructor whose parameters match the examples, initializing every instance variable.
- Each method with exactly the header implied by the examples: name, parameter types, return type.
- Update the state in the methods that should change it.
- Return values; do not print them unless told to.
Common mistakes
- Declaring instance variables public, or forgetting to declare them at all.
- Re-declaring an instance variable inside the constructor (
double balance = startingBalance;), which creates a local variable and leaves the real one at its default. - Giving a constructor a return type.
- Printing where a return is required.
- Making a value local when it must persist between calls.
- Forgetting
thisis unnecessary unless names clash.
Check yourself
Why are instance variables normally declared private?
Show the answer
So that the class controls how its data is read and changed
Encapsulation lets methods validate changes and hides the representation.
6For top marks
- In free-response class-writing questions, declare all instance variables
private, write the constructor to initialise every instance variable, and match method headers exactly to the specification. - Do not redeclare instance variables inside the constructor (
double balance = start;creates a local variable and leaves the field at 0.0). - Keep methods focused on one task.
- Use
toString()to return a String description of an object;System.out.println(obj)calls it automatically.
public String toString() { return owner + ": $" + balance; }
Check yourself
What is wrong with a constructor containing double balance = start;?
Show the answer
It creates a local variable, so the instance variable is not set
Shadowing the field.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera