Topic 3.7 — Class Variables and Methods

Goal: distinguish between instance variables/methods and class (static) variables/methods, and explain how static members belong to the class itself (shared by all objects).

The big idea

Instance members belong to each object (each object gets its own copy). Class (static) members belong to the class (one shared copy for everyone).

On AP, you’ll often be asked: “Is this information shared across all objects, or unique per object?”

Instance vs static (quick compare)

Member type Keyword How many copies? Accessed like
Instance variable (none) one per object obj.field
Static (class) variable static one per class ClassName.field
Instance method (none) runs on one object obj.method()
Static (class) method static runs without an object ClassName.method()

Static variable example (shared counter)

A common use of a static variable is to track a value shared by all objects, like “how many objects exist.”

public class Student {
  private String name;           // instance variable (unique per object)
  private static int count = 0;  // class variable (shared)

  public Student(String n) {
    name = n;
    count++;
  }

  public static int getCount() { // class method
    return count;
  }
}

How to access static members

  • Preferred: use the class name for static members.
  • This makes it clear the value is shared.
int total = Student.getCount();

Static methods can’t use instance fields directly

A static method doesn’t run “on” any one object, so it can’t access instance variables unless it has an object reference.

public static void bad() {
  // System.out.println(name); // ❌ name is instance variable
}

Instance method example (uses object state)

Instance methods usually read or change instance variables.

public void changeName(String newName) {
  name = newName; // instance variable
}

When to choose static?

  • Use instance when each object needs its own data (like name, score).
  • Use static when the value is shared across all objects (like a counter, a constant, or a shared setting).
  • Use static methods for utility/helper methods (often in other units, like Math).

Quick self-check

  1. How many copies of a static variable exist?
  2. How many copies of an instance variable exist?
  3. Why can’t a static method directly use an instance variable?
  4. Should you access static members using an object or the class name?
  5. Give one example of data that should be static.

← Back to Unit 3 topics