Static Methods and Variables
In Java, the static
keyword means โthis member belongs to the class itself, not to any specific object.โ
When you mark a field or method as static:
You do not need to create an instance to use it.
The field or method exists once per class, shared by all objects.
Key point:
Non-static members belong to each object, but static members belong to the class.
Where does this matter?
Static variables are used for data that must be shared across all instances โ like a counter that tracks how many objects exist.
Static methods are used for tasks that donโt depend on any particular objectโs state โ like utility functions (Math.sqrt()
).
A static field is a variable that all instances of a class share.
Example: counting how many objects have been created.
Key point:
count
is declared static.
Every time you create a Counter
object, it increases count
.
The field is shared by all instances โ not duplicated.
Without static
, each object would have its own separate count
, which wouldnโt work here.
A static method can be called without creating an object.
You can think of it as a class-level tool.
Classic example: main()
itself is static:
Static methods are useful for:
Utility tasks (Math.max()
, Math.abs()
).
Factory methods that create instances.
Helper functions that donโt need object data.
Example:
Key points:
You call it like MathHelper.square(5)
, no object needed.
Static methods cannot access non-static fields directly โ because they donโt belong to any specific object.