Class Variables
& Methods
Understand how static members belong to the class itself, not individual objects: shared data, utility methods, and the power of the static keyword in Java.
What Are Class Variables?
A class variable (also called a static variable) is a variable declared with the static keyword. It belongs to the class itself, not to any single object. Every instance of the class shares the same copy of that variable.
What Are Class Methods?
A class method (also called a static method) is a method declared with the static keyword. It can be called without creating an object of the class. It can only access other static members directly.
Why Does Static Matter?
The Memory Model
The static Keyword Rule
Access Rules at a Glance
Static vs Instance
| Static (Class) | Instance (Object) | |
|---|---|---|
| Declared with | static keyword | No static keyword |
| Belongs to | The class itself | Each individual object |
| Copies in memory | One (shared) | One per object |
| Accessed via | ClassName.member | objectName.member |
| Can use "this"? | No | Yes |
| Example | Math.PI | dog.name |
When to Use Static
Example 1: Object Counter
One ticket office counter, many fixed ticket IDs
Each issued ticket keeps its own number while one class counter advances. Shared class state and separate instance state serve different purposes.Copy the number, then advance the counter
The Ticket constructor copies nextNumber into the new instance and then increments the shared counter. Tickets keep IDs 1 and 2 while nextNumber becomes 3. This counter records constructions.Example 2: Utility Class
Example 3: Static Final Constants
Calling Static Members
Scope and Lifetime
Common Mistakes
Question 1 of 5
Which keyword makes a variable or method belong to the class rather than to individual objects?
Question 2 of 5
Consider the following class:
public class Counter {
private static int count = 0;
public Counter() { count++; }
public static int getCount() { return count; }
}
The following code is executed in main:
Counter a = new Counter();
Counter b = new Counter();
Counter c = new Counter();
System.out.println(Counter.getCount());
What is printed?
Question 3 of 5
A static method cannot directly access which of the following?
Question 4 of 5
Consider the following class:
public class Temp {
private double degrees;
public Temp(double d) { degrees = d; }
public static double toFahrenheit(double c) {
return c * 9.0 / 5.0 + 32;
}
public double getDegrees() { return degrees; }
}
Which line of code will cause a compile error?
Question 5 of 5
Which of the following is the best reason to declare a variable as static final?