Static & Non-Static Variables and Methods
Static vs Non-Static Variables & Methods
Static (class) members belong to the class itself, shared across all instances. Non-static (instance) members belong to each object. Each instance has its own copy.
Choosing between them affects state sharing, memory usage, and how you design your classes.
Comparison of Static and Instance Members
| Static Member | Instance Member | |
|---|---|---|
| Belongs To | The class itself | Each object (instance) |
| Declaration | static keyword (Java)class variable in Python |
No keyword; defined per instance |
| Access | ClassName.member or object.member |
object.member only |
| Use Case | Shared counters, configuration | Object-specific state and behaviour |
| Memory | One copy per class | One copy per instance |
Usage Scenarios for Static vs Instance Members
-
Static Members
• Application-wide configuration: e.g. aMAX_USERSconstant that applies to all user sessions.
• Shared counters: e.g. tracking the total number of active connections or instantiated objects across the whole program. -
Instance Members
• User profile data: each `User` object holds its own `username`, `email`, and settings.
• Bank account balances: each `BankAccount` instance maintains its own `balance` independently of other accounts.
Example: Static vs Instance Members
class Counter:
total_count = 0 # class (static) attribute
def __init__(self, id):
self.id = id # instance attribute
Counter.total_count += 1
@classmethod
def get_total_count(cls):
return cls.total_count
if __name__ == "__main__":
c1 = Counter(101)
c2 = Counter(202)
print("c1 ID:", c1.id) # 101
print("c2 ID:", c2.id) # 202
print("Total Count:", Counter.get_total_count()) # 2
public class Counter {
private static int totalCount = 0; // shared across all instances
private int id; // unique per instance
public Counter(int id) {
this.id = id;
totalCount++;
}
public static int getTotalCount() {
return totalCount;
}
public int getId() {
return id;
}
public static void main(String[] args) {
Counter c1 = new Counter(101);
Counter c2 = new Counter(202);
System.out.println("c1 ID: " + c1.getId()); // prints 101
System.out.println("c2 ID: " + c2.getId()); // prints 202
System.out.println("Total Count: " + Counter.getTotalCount()); // prints 2
}
}
Key Takeaways
- Static members are shared across all instances and accessed via the class.
- Instance members are unique to each object and accessed via the instance.
- Use static for counters, configuration, or utility methods that should not vary per object.
- Use instance members for data and behaviour specific to each object’s state.