Static Members in Java: Explanation & Practice
Use static fields and methods
Problem summary
Create a Counter class with a static count that tracks how many instances are created.
Starter code
// Create Counter class with:
// - static int count (starts at 0)
// - constructor increments count
// - static getCount() method
public class Main {
public static void main(String[] args) {
// Create 3 Counter objects
// Print: Total counters: 3
}
}Expected output and test cases
- Count instances
Total counters: 3
Hints
- Static fields are shared across all instances
- Increment static count in constructor
- Access static method using ClassName.method()
Related OOP Basics exercises
- Practice Using Constructors in Java
- Practice Getters and Setters in Java
- Practice Method Overloading in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler