What is the static keyword in Java?
A static member belongs to the class. You use it with the class name and no object is needed.
- Static field: one copy shared by all the objects (like a counter).
- Static method: can not use
thisor instance fields (mainis static). - Static block: runs once when the class is loaded.
- Static nested class: a class inside a class, without a link to the outer object.
class Counter {
static int total = 0;
Counter() { total++; }
}
public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
System.out.println(Counter.total);
}
}
Output
2
See Java static and this.
Learn more about the similar topics:
| Tutorials |
|---|
| Java Classes and Objects |
| Java Constructors |
| Java static and this Keywords |
| Java Encapsulation and Access Modifiers |
| Java Inheritance |
| Java Polymorphism |
| Java Abstract Classes |
| Exercises & Assignments |
|---|
| Build a BankAccount class |
| Calculate areas with inheritance and polymorphism |
| Use a sealed interface and pattern matching |