Rayan Alkhelaiwi Rayan Alkhelaiwi - 4 months ago 9
Java Question

What is the use of "static" for a "final" variable?

I'm reviewing a class and I noticed there is a final double variable called Kilograms_Per, but there is static before the declaration, what is the use of static since the variable is final? Here is the segment:

public static final double KILOGRAMS_PER_POUND = 0.45359237;

Answer

static means that the variable is associated with the class, not an instance of the class.

final means that the variable cannot be reassigned after it's been reinitialized. If you tried to change KILOGRAMS_PER_POUND again, you would get a compiler error.

static and final are orthogonal to one another. Suppose you have this class:

public class Foo {
  public static final double KILOGRAMS_PER_POUND = 0.45359237;
}

The variable KILOGRAMS_PER_POUND can be:

  1. static only, meaning the variable is associated with the object, so it is referenced as Foo.KILOGRAMS_PER_POUND from another class. Because it is not final, the variable can also be reassigned, e.g. Foo.KILOGRAMS_PER_POUND = 3.14.

  2. final only. Because it is not static meaning that the variable must be reference by an instance of the class, e.g. Foo foo = new Foo(); System.out.println(foo.KILOGRAMS_PER_POUND); Because the variable is final, it cannot be reassigned.

  3. static and final. Because it is static, it is referenced as Foo.KILOGRAMS_PER_POUND from another class. Because it is final, it cannot be reassigned.