Static and instance members
An instance field exists once per object. A static field exists once for the whole class and is shared by every object.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Static members belong to the class itself. You reach them through the class name, Visitor.Count, and they exist even before any object is created.
Code
var a = new Visitor("Asha");
var b = new Visitor("Ravi");
var c = new Visitor("Meera");
Console.WriteLine(Visitor.Count); // 3
class Visitor {
public static int Count; // one copy, shared by the class
public string Name; // one copy per object
public Visitor(string name) { Name = name; Count++; }
}class Visitor {
static int count; // one copy, shared by the class
String name; // one copy per object
Visitor(String name) { this.name = name; count++; }
}
public class Main {
public static void main(String[] args) {
Visitor a = new Visitor("Asha");
Visitor b = new Visitor("Ravi");
Visitor c = new Visitor("Meera");
System.out.println(Visitor.count); // 3
}
}class Visitor {
public:
static inline int count = 0; // one copy, shared by the class
string name; // one copy per object
Visitor(string name) : name(name) { count++; }
};
int main() {
Visitor a("Asha");
Visitor b("Ravi");
Visitor c("Meera");
cout << Visitor::count << "\n"; // 3
}class Visitor:
count = 0 # one copy, shared by the class
def __init__(self, name: str):
self.name = name # one copy per object
Visitor.count += 1
a = Visitor("Asha")
b = Visitor("Ravi")
c = Visitor("Meera")
print(Visitor.count) # 3Tips
- A static method has no "this", so it cannot touch instance fields without being given an object.
- Shared mutable static state is a common source of bugs in multi-threaded code.
In the .NET library
A static class such as Math or Console cannot be instantiated at all. In a web app, static fields are shared across every request, so prefer dependency injection with a singleton lifetime.