APrep Open the app

AP Computer Science A · Unit 3: Class Creation

3.7 Static Variables and Methods

What makes a variable or method static

Static members belong to the class itself, not to any individual object. All instances share one copy of a static variable, so changing it through one object affects what all objects see. Declared with the `static` keyword, e.g., `static int count;`. Non-static (instance) members exist separately for each object.

Calling static members

Static methods and variables are accessed using the class name (e.g., `ClassName.methodName()`), not an object reference, though Java allows calling them through an object too. Static methods cannot access instance variables or call instance methods directly because they don't operate on a specific object — there's no `this`.

Common uses

Static variables often track class-wide data, like a counter of how many objects have been created (incremented in the constructor). Static methods are used for utility/helper operations that don't need object state, like `Math.sqrt()`. The `main` method is static because it runs before any objects exist.

Key terms

Static variable
A variable shared by all instances of a class; only one copy exists regardless of how many objects are created.
Static method
A method that belongs to the class itself and can be called without creating an object; cannot access instance variables/methods directly.
Calling a static member
Typically done with ClassName.memberName, though it can also be accessed through an object reference.
Why static methods can't use 'this'
Because static methods are not tied to any specific object instance, there is no current object to refer to.
Common use of static variables
Tracking class-wide data, such as a counter incremented in the constructor to count how many objects have been created.

Try an AP-style question

Code

public class Student {
    private static int count = 0;
    public Student() { count++; }
}
...
new Student(); new Student(); new Student();

What is count?

  1. An error
  2. 0
  3. 1
  4. 3
Show the answer

D. Shared by all objects.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 3.7 free in APrep