AP Computer Science A · Class creation
Static variables and methods
1Static variables
A static variable (class variable) belongs to the class, not to any one object. All objects share a single copy.
public class Ticket {
private static int nextNumber = 1;
private int number; public Ticket() {
number = nextNumber;
nextNumber++;
}
}
Each new Ticket gets a unique number; nextNumber counts how many have been made.
Use static variables for data shared by all objects: counters, shared constants (public static final double PI = 3.14159;).
Check yourself
How many copies of a static variable exist when 50 objects have been created?
Show the answer
One
Shared by the class.
2Static methods
A static method belongs to the class and is called with the class name: Math.sqrt(9), Integer.parseInt("42").
public static double average(int a, int b) {
return (a + b) / 2.0;
}
Static methods:
- do not have a
thisobject; - cannot directly access instance variables or call instance methods (there is no object to use);
- can access static variables and call other static methods.
A static variable lives in the class and is shared; instance variables live in each object
Check yourself
Why can't a static method use an instance variable directly?
Show the answer
There is no specific object whose variable it could use
No this.
3Instance versus static
- Instance methods can use both instance and static members.
- Static methods can use only static members (unless they are given an object reference as a parameter).
Worked example:
public class Circle {
private static int count = 0;
private double r;
public Circle(double radius) { r = radius; count++; }
public static int getCount() { return count; }
public double area() { return Math.PI * r * r; }
}
new Circle(1); new Circle(2);→Circle.getCount()returns 2.area()must be called on an object:c.area().- Writing
return r;insidegetCountwould not compile.
Check yourself
Which call is correct for the static method getCount in class Circle?
Show the answer
Circle.getCount()
Class name.
4When to use static
Make a method static when it does not depend on any object's state: utility calculations, helper methods in a class of tools, main.
Make a variable static when the value is shared by all objects (a running total, a count, a constant).
Check yourself
A method that converts Celsius to Fahrenheit, using no instance data, should be:
Show the answer
static
No object needed.
5Going deeper: one copy for the class, and what static methods may not do
Instance members belong to an object; static members belong to the class.
A static variable has one copy shared by every object of the class. It exists even if no object has been created.
public class Ticket {
private static int nextNumber = 1;
private int number;
public Ticket() {
number = nextNumber;
nextNumber++;
}
public int getNumber() {
return number;
}
public static int getIssued() {
return nextNumber - 1;
}
}
Worked example (trace):
Ticket a = new Ticket();
Ticket b = new Ticket();
Ticket c = new Ticket();
System.out.println(a.getNumber() + " " + c.getNumber() + " " + Ticket.getIssued());
- Creating a: number = 1; nextNumber becomes 2.
- Creating b: number = 2; nextNumber becomes 3.
- Creating c: number = 3; nextNumber becomes 4.
- Output:
1 3 3.
Each ticket has its own number; all share one nextNumber.
Typical uses of static variables
- Counting objects created.
- Handing out unique IDs.
- Constants shared by all:
public static final double TAX_RATE = 0.07;.finalmeans it cannot be reassigned; public constants are safe to expose.
A static method is called on the class, not on an object: Ticket.getIssued(), Math.sqrt(2.0).
What a static method cannot do
- It has no
this: there is no object it is working on. - So it cannot use instance variables or call instance methods directly.
- It can use static variables, its parameters and local variables, and call other static methods.
- It can work with objects passed to it as parameters.
public static int broken() {
return number; // does not compile: number is an instance variable
}
Instance methods can use everything: instance variables, static variables, and both kinds of method.
When should a method be static?
- It does not depend on any particular object's state.
- Utility calculations: everything in
Math. - It reads or updates only static data.
mainis static, because it runs before any object exists.
When should a variable be static? Ask: is this a fact about each object (a student's name) or about the class as a whole (the number of students created)? Making per-object data static is a serious bug: every object would overwrite the same value.
Worked example (the bug):
public class Player {
private static int score;
public void addPoints(int p) {
score += p;
}
public int getScore() {
return score;
}
}
// elsewhere:
Player p1 = new Player();
Player p2 = new Player();
p1.addPoints(10);
p2.addPoints(5);
System.out.println(p1.getScore());
- Both players share one
score. - After the two calls it is 15.
- Output:
15, not 10.scoreshould not be static.
Calling conventions
- Static method from another class:
ClassName.method(). - Static method from inside its own class: just
method(). - Calling an instance method needs an object: from
main, writeobj.method().
A common compile error: calling an instance method from main without an object. Either create an object or make the method static.
Static and memory: instance variables are stored inside each object; a static variable is stored once, with the class.
Constants in the exam's classes: Integer.MAX_VALUE and Integer.MIN_VALUE are public static final variables of the Integer class.
Common mistakes
- Using an instance variable in a static method.
- Making a variable static when each object needs its own.
- Calling an instance method with the class name.
- Thinking each object gets its own copy of a static variable.
- Using
thisin a static method.
Check yourself
A class has private static int count; and its constructor contains count++;. After four objects have been created, what is count?
Show the answer
4
All objects share the single static variable.
6For top marks
- In free-response, read whether a method is labelled
static; if so, it cannot usethisor instance variables. - Free-response "array/ArrayList" questions often ask for static helper methods that take everything they need as parameters.
- Update static counters in the constructor so each new object is counted.
public static finalconstants are fine to make public because they cannot change.
public static boolean isPrime(int n) takes n as a parameter and uses only local variables.
Check yourself
Which statement would NOT compile inside a static method of Circle?
Show the answer
return r * r;
r is an instance variable.
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