Static Members
The static keyword is used to declare members (fields
and methods) that belong to the class itself, rather than to
instances of the class.
Static Fields
A static field is shared by all instances of the class.
class Counter {
static int count = 0; // Shared
Counter() {
count++;
}
}
Static Methods
Static methods can be called without creating an object available. They cannot access instance fields.
class MathUtils {
static int add(int a, int b) {
return a + b;
}
}
// Usage:
MathUtils.add(5, 10);
Full Example
Output
Click Run to execute your code
Enjoying these tutorials?