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

  1. Static fields are shared across all instances
  2. Increment static count in constructor
  3. Access static method using ClassName.method()

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler