What Is an Instance in Java?
"Instance" is a synonym for object: a concrete realisation of a class in memory. "Create an instance of ArrayList" means call new ArrayList<>() and get back a real, working list object. The term is especially common when distinguishing instance (per-object) members from static (per-class) members.
Instance vs class-level (static)
public class Lamp {
// Instance field β each Lamp object has its own:
private boolean on = false;
// Static field β ONE copy shared by ALL Lamp objects:
private static int totalLamps = 0;
public Lamp() { totalLamps++; }
// Instance method β operates on THIS lamp:
public void toggle() { on = !on; }
// Static method β operates on the class:
public static int getTotalLamps() { return totalLamps; }
}
Lamp l1 = new Lamp();
Lamp l2 = new Lamp();
l1.toggle();
System.out.println(l1.on); // true
System.out.println(l2.on); // false (independent)
System.out.println(Lamp.getTotalLamps()); // 2 (shared)
instanceof operator
Test whether an object is an instance of a specific class at runtime:
Object obj = "Hello";
if (obj instanceof String s) { // pattern matching (Java 16+)
System.out.println(s.length()); // 5
}
"Instance variable" and "instance method"
- Instance variable (aka instance field) β a field declared without
static. Each object gets its own copy. - Instance method β a method declared without
static. It can accessthisand the object's instance fields.
Lifecycle of an instance
- Memory allocated on the heap when
newis called. - Fields initialised to defaults (
0,false,null). - Constructor runs, setting fields to their intended starting values.
- The object lives until no references point to it.
- Garbage collector reclaims the memory.
Common phrasing
- "Create an instance" = call
new ClassName() - "An instance of
Map" = any object whose type implements theMapinterface (HashMap,TreeMap, etc.) - "Instance fields" = non-static fields, unique per object
- "Singleton" = a class designed to have exactly one instance