Static vs. Instance Members
Distinguish static and instance variables and methods, class-level state, object-level state, and appropriate method design.
A lesson of AP Computer Science A, in Objects and Classes, about 10 minutes.
By the end of this lesson, you will be able to distinguish static from instance variables and methods, explain when to use each, and avoid common static/instance confusion errors.
The Two Kinds of Members
Every field (variable) and method in a Java class is either static or instance (non-static).
Instance members: belong to a specific object; each object has its own copy.
Static members: belong to the class itself; shared by all objects of that class.
Instance Variables
public class Dog {
private String name; // instance variable — each Dog has its own name
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
}
Dog d1 = new Dog("Rex", 3);
Dog d2 = new Dog("Bella", 5);
// d1.name = "Rex"; d2.name = "Bella" — separate copies
Each object created from the class has its own set of instance variables.
Static Variables
public class Dog {
private String name;
private static int count = 0; // tracks total dogs created
public Dog(String name) {
this.name = name;
count++; // increments the SHARED counter
}
public static int getCount() {
return count;
}
}
Dog d1 = new Dog("Rex"); // count = 1
Dog d2 = new Dog("Bella"); // count = 2
System.out.println(Dog.getCount()); // 2
A static variable (class variable) is shared by all objects of the class. There's only one copy, regardless of how many objects exist.
When to use static variables: for data that belongs to the class concept, not to any individual object — counters, constants, configuration.
Constants are almost always static: public static final double PI = 3.14159;
Instance Methods
public String getName() {
return name; // accesses THIS object's name field
}
d1.getName() // "Rex"
d2.getName() // "Bella"
Instance methods operate on a specific object and can access its instance variables.
Static Methods
public static int max(int a, int b) {
return (a > b) ? a : b;
}
// Called on the class name, not an object:
int m = ClassName.max(5, 10);
// Or just max(5, 10) within the same class.
Static methods do not belong to any specific object. They cannot access instance variables or call instance methods (without an object reference).
Calling static methods: use the class name: , .