codegurukool.com · Free coding tutorials & online compiler

Home › Java Tutorial › Java static members

Java static members

Shared by every object.

A static field or method belongs to the class itself, not to one object. Use it for counters, constants and helper methods. Access it with the class name, like Counter.count.

Example code

class Counter {
  static int count = 0;

  Counter() {
    count++;
  }
}

public class Main {
  public static void main(String[] args) {
    new Counter();
    new Counter();
    new Counter();
    System.out.println(Counter.count);
  }
}

Run this code in the online editor

← Java classes and objectsJava encapsulation →