Fundamentals (Docs)


Static keyword

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. 

Fields that have the static modifier in their declaration are called static fields or class variables. 
They are associated with the class, rather than with any object. 

Any object can change the value of a class variable, but class variables can also be manipulated without creating an
 instance of the class.
	public class Bicycle{
		private int speed;
		private static int numberOfBicycles = 0; // add a class variable using static keyword
		private int id;

		public Bicycle() {
			id = ++numberOfBicycles; // increment number of Bicycles and assign ID number
	Bicycle.numberOfBicycles // This makes it clear that they are class variables


The final modifier indicates that the value of this field cannot change.
	static final double PI = 3.141592653589793;
Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so.

Static Initialization Blocks

If initialization requires some logic, simple assignment like this is inadequate.

	 public static int capacity = 10;  // initialize to 10

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword.
	static {
	    // initialization code goes here

There is an alternative to static blocks - you can write a private static method:

	class Whatever {
	    public static varType myVar = initializeClassVariable();
	    private static varType initializeClassVariable() {
		//initialization code goes here

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.