AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/3/3-7)
Unit 3 · Topic 3.7
3.7 Class Variables and Methods
Some data belongs to a class as a whole, not to any one object. This topic covers static class variables, which every object shares, static class methods, which run without an object, and final, which makes a variable's value permanent.
Key terms
- class variable
- class method
staticfinal- shared copy
Class variables
A class variable is declared with the keyword static. There's only one copy, and it belongs to the class itself. Every object of the class shares it, so a change made through one object is seen by all of them. An instance variable, by contrast, has a separate copy inside every object.
A classic use is counting how many objects have been created: the constructor adds 1 to a static counter every time it runs.
public class Ticket
{
public static final int MAX_TICKETS = 500;
private static int issued = 0;
private int number;
public Ticket()
{
issued++;
number = issued;
}
public int getNumber()
{
return number;
}
public static int getIssued()
{
return issued;
}
public static int ticketsLeft()
{
return MAX_TICKETS - issued;
}
}
Each ticket gets its own number (an instance variable), but issued is a single shared count.
Instance versus static
This table sums up the differences.
| Question | Instance variable or method | Class (static) variable or method |
|---|---|---|
| How many copies? | one per object | one for the whole class |
| How do you call or use it from outside? | through an object, like a.getNumber() | through the class name, like Ticket.getIssued() |
| Can it use instance variables? | yes | only through an object passed in |
| Does it have this? | yes | no |
Accessing static members
A public class variable or class method is used from outside the class with the class name and a dot, as in Ticket.MAX_TICKETS or Ticket.getIssued(). You've already done this with Math.sqrt and Integer.MAX_VALUE.
What class methods can and can't do
A class method is declared static. It can use class variables and call other class methods.
There's no object behind a static method call, so a static method can't use instance variables or call instance methods directly. Whose number would it use? It can only work with an object's data if an object is passed to it as a parameter and it calls methods on that object.
final
A variable declared final can't be changed after it gets its value. Trying to assign to it again is a compile error. Constants like MAX_TICKETS are usually public static final, written in capital letters with underscores. They're safe to make public because nobody can change them.
Worked examples
Try each one yourself first, then open the solution.
- Example 1
A shared counter
Using the
Ticketclass above, what does this code print?Ticket a = new Ticket(); Ticket b = new Ticket(); Ticket c = new Ticket(); System.out.println(a.getNumber() + " " + c.getNumber()); System.out.println(Ticket.getIssued() + " " + Ticket.ticketsLeft());Show the solutionHide the solution
- Step 1:
issuedstarts at 0 and is shared by all tickets. - Step 2: Creating
amakesissued1, anda's ownnumberis 1. Creatingbmakesissued2 and givesbnumber 2. Creatingcmakesissued3 and givescnumber 3. - Step 3: The first line prints
a's andc's numbers: 1 and 3. - Step 4:
Ticket.getIssued()returns the shared count, 3, andTicket.ticketsLeft()is 500 − 3 = 497.
Answer: Two lines:
1 3, then3 497. - Step 1:
- Example 2
Which one won't compile?
Which of these causes a compile error? I. A static method in
Ticketthat returnsnumber * 2. II. Code in another class that runsTicket.MAX_TICKETS = 600;. III. A static method in another class that takes twoTicketparameters and returns whether theirgetNumber()values are equal.Show the solutionHide the solution
- Step 1: I:
numberis an instance variable. A static method has no object, so it can't usenumberdirectly. Compile error. - Step 2: II:
MAX_TICKETSisfinal, so it can't be assigned a new value. Compile error. - Step 3: III: the method uses objects passed in as parameters and calls their public
getNumber()method. That's allowed. It compiles. - Step 4:
public static boolean sameNumber(Ticket x, Ticket y) { return x.getNumber() == y.getNumber(); }
Answer: I and II cause compile errors; III compiles.
- Step 1: I:
Common mistakes
- Using an instance variable inside a static method. A static method has no object to take it from.
- Making a counter an instance variable. Then each object counts only itself, and every count stays at 1.
- Trying to change a
finalvariable after it's set.
On the exam
- Expect questions that create several objects and ask about a shared static counter. Remember there's only one copy, no matter how many objects exist.
- On free-response Question 2, use a static variable only if the description says a value is shared by all objects.
Connected topics
Videos
Check yourself
4 questions on 3.7 Class Variables and Methods. Pick an answer to see if you got it, and why.
public class Ticket
{
private static int count = 0;
private int id;
public Ticket()
{
count++;
id = count;
}
public int getId()
{
return id;
}
public static int getCount()
{
return count;
}
}What is printed as a result of executing the following code segment, which appears in a class other than Ticket?Ticket a = new Ticket();
Ticket b = new Ticket();
Ticket c = new Ticket();
System.out.println(a.getId() + " " + c.getId() + " " + Ticket.getCount());
Which of the following methods, if added to the Ticket class, causes a compile-time error?
Consider the following code segment.final int LIMIT = 10;
int total = 4;
total += LIMIT;
LIMIT = 12;
System.out.println(total);What is the result of compiling and running the code segment?
Consider the following class.public class Bank
{
public static final double RATE = 0.05;
}Which of the following expressions, appearing in a different class, correctly uses the value of RATE?
0 of 4 answered