AP Computer Science A · Unit 3 lecture · Part 7 of 10 · 8 min

3.7 Class variables and methodsstatic: one copy for the whole class

Mr. Thompkins
A sandwich shop wants every order to get its own number automatically: 101, 102, 103 and so on. Each order knows its own number. But who remembers which number comes next? Not any one order. The class does.

Instance variables give every object its own copy. A static variable, also called a class variable, belongs to the class itself, so there is exactly one copy, shared by every object. Any object that changes it changes it for all of them. That makes static variables perfect for counters and shared settings.

1public class Order2{3    public static final int MAX_ITEMS = 5;14    private static int placed = 0;25    private int number;6    private int items;78    public Order(int items)9    {10        placed++;311        number = 100 + placed;312        this.items = items;13    }1415    public static boolean isValid(int qty)416    {17        return qty >= 1 && qty <= MAX_ITEMS;18    }1920    public static int getPlaced() { return placed; }21    public int getNumber() { return number; }22}23// in a client class24System.out.println(Order.isValid(7));525Order o1 = new Order(2);26Order o2 = new Order(4);27Order o3 = new Order(1);28System.out.println(o1.getNumber() + " " + o3.getNumber());29System.out.println(Order.getPlaced() + " " + Order.MAX_ITEMS);
  1. line 3 A class constant: static final, one shared value that never changes
  2. line 4 A class variable: one counter shared by every Order
  3. line 10-11 Each constructor bumps the shared counter, then copies it
  4. line 15 A class method: uses only its parameter and static data
  5. line 24 Called on the class name, before any Order exists
output › false 101 103 3 5
placed is shared by every Order; number and items belong to each order.
Order class: one shared copyplaced 3MAX_ITEMS 5number 101items 2number 102items 4number 103items 1o1o2o3each object: its own number and items
One shared counter above, three objects below. Each constructor bumped placed, then copied it into number.
?Wait, what does final do again?
final means a variable can be assigned only once. A static final variable is a class constant, like MAX_ITEMS, and by habit its name is in capital letters. Trying to assign it later, as in Order.MAX_ITEMS = 9;, is a compile error: cannot assign a value to final variable MAX_ITEMS.

A static method, also called a class method, belongs to the class too. You call it on the class name, Order.isValid(7), and you don't need any object to exist. You've been doing this for two units: Math.sqrt, Math.abs and Integer.parseInt are all static methods.

?Wait, why is main always static?
When a program starts, no objects exist yet, so Java needs a method it can call on the class alone. That's main: public static void main(String[] args). It's also why a helper method you call straight from main has to be static.

Here's the catch. A static method runs without any object, so it has no instance variables to look at. It can use its parameters, local variables and static variables, and it can call other static methods. It cannot use an instance variable or call an instance method directly. Instance methods, on the other hand, can use everything: their own object's data and the static data too.

1// added to Order: a static method that uses an2// instance variable3public static int getItems()4{5    return items;16}
  1. line 5 error: non-static variable items cannot be referenced from a static context
output › compile error: whose items? A static method has no object
A static method asking for an instance variable. The compiler can't tell which object's items you mean.
Pause and think
Suppose the word static were removed from placed, so each Order had its own copy. What would o1.getNumber() and o3.getNumber() return?
I thought about it. Show me
Both 101. Each new Order would start its own placed at 0, bump it to 1 and store 101. Only a shared counter can remember how many orders came before. (getPlaced, still static, would then fail to compile, since placed would be an instance variable.)
Trace the shared counter

Assume no Orders exist yet. What does this print?

Order a = new Order(3);
Order b = new Order(9);
Order c = new Order(1);
System.out.println(Order.isValid(9) + " " + b.getNumber());
System.out.println(Order.getPlaced() - a.getNumber());
  1. a: placed becomes 1, number 101. b: placed 2, number 102. c: placed 3, number 103.
    Why?
    The constructor doesn't check isValid, so new Order(9) is built like any other.
  2. Order.isValid(9): 9 <= 5 is false, so false. b.getNumber() is 102. First line: false 102.
  3. Order.getPlaced() is 3 and a.getNumber() is 101, so 3 - 101 = -98.

Answer: false 102, then -98.

Stuck? Get a hint
  1. Keep one box for placed and update it at every new.
  2. Each number is 100 plus placed right after it's bumped.
  3. isValid only accepts 1 to 5.
Check yourself
Which numbered line causes a compile-time error?
public class Bus
{
    private static int riders = 0;
    private int seats;

    public Bus(int seats) { this.seats = seats; }

    public static void board()
    {
        riders++;          // line 1
        seats--;           // line 2
    }

    public int open()
    {
        return seats - riders;  // line 3
    }
}
  1. ALine 1
  2. BLine 2
  3. CLine 3
  4. DNone of them
Show the answer

B. board is static, so it has no object, and seats is an instance variable: line 2 doesn't compile. Line 1 is fine because riders is static. Line 3 is fine because an instance method can use both kinds of variables, which is the trap in the third choice.

  • static variable: one copy shared by the whole class. Use it for counters and shared values.
  • static final: a class constant that can't be reassigned.
  • Call static methods on the class name: Order.isValid(7), Math.sqrt(2).
  • A static method can't use instance variables or call instance methods directly. Instance methods can use static data.