Class variables
- Java course
- Intermediate
- Lesson 33/116
- 4 min
Learn to share class-level variables.
Class variables
Static fields are also called class variables. Because they belong to the class and are shared by all instances. Instance variables are separate per instance; class variables are single.
Example: class Player { static int total = 0; String name; }. Here total is a class variable; all Player instances share the same total. name is an instance variable; each instance has its own name. Player.total accesses the class variable, p.name the instance variable. Class variables are used for counters, configuration and shared state.
Instance vs class variable
An instance variable is specific to each instance; a class variable is shared by all instances. An instance variable is created anew with new for each instance; a class variable is created once when the class loads.
Example: Player p1 = new Player(); Player p2 = new Player();. p1.name and p2.name hold different values; because name is an instance variable. But Player.total is a single value; p1 and p2 see the same total. Changing the class variable affects all instances. This distinction determines whether data is shared at the instance or class level.
Practice Add a class variable to Player
Define a class Player. Add a static int total = 0 class variable and a String name instance variable. Write a constructor; assign name = n; and run total++. In main create two Player instances and print the value of Player.total.
Starter code
// Define the Player class
// Add a static total and a name field
// Increment the counter in the constructorSample solution
class Player {
static int total = 0;
String name;
Player(String n) {
name = n;
total++;
}
public static void main(String[] args) {
Player a = new Player("Alex");
Player b = new Player("Sam");
System.out.println(Player.total);
}
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the class variable definition
class Player {
____ int total = 0;
String name;
}
class Player {
static int total = 0;
String name;
}
Explanation: total is a class variable.
2 Match variable types
| Term | Meaning |
|---|---|
static int total |
Class variable |
String name |
Instance variable |
Player.total |
Class-name access |
p1.name |
Instance access |
3 How many copies does a static int total field create?
- One per instance
- No copies at all
- One for the class Correct answer
- One per method
Explanation: One for the class — a static field is shared by all instances.