What is the difference between instance and static members of a class?
An instance member belongs to each object and has a separate copy per object. A static member belongs to the class itself, exists once, and is shared by every object.
Explain it simply
Think of a college hostel. Each student's own bed number is personal (instance). The hostel's total headcount board in the lobby is one board shared by everybody (static).
Instance fields live inside each object. Static fields live with the class and are loaded once. A static method can run without any object, so it cannot touch instance fields directly; an instance method can use both.
Example
class Ticket {
static int sold = 0; // shared
int seatNo; // per object
Ticket() {
sold++;
seatNo = sold;
}
}
Ticket t1 = new Ticket();
Ticket t2 = new Ticket();
System.out.println(Ticket.sold); // prints: 2
System.out.println(t1.seatNo); // prints: 1
System.out.println(t2.seatNo); // prints: 2sold is one variable seen by both tickets. seatNo is a different variable inside each.
What to say in the interview
"Instance members are tied to an object and each object has its own copy. Static members are tied to the class, exist once, and can be accessed without creating an object. Static methods cannot use this or instance fields. I use static for constants and utilities, not for state that should differ per object."
Common mistakes
- Using static for everything to avoid creating objects. That makes code hard to test and extend.
- Calling an instance method from main without creating an object.