Java Static Methods, Variables, Final Variables (Constants)

Static Methods
The keyword static lets a method run without any instance of the class. A static method’s behavior is not dependent on an instance variable, so no instance / object is required. Static methods cannot use non-static (instance) variables, nor can they use non-static methods. Non-static method behavior relies on instance variables, which rely on an instantiated object. Even if a non-static method does not use any instance variables, you still cannot invoke it from within a static method. Think about what might happen if in the future you changed the non-static method to use an instance variable, or if the non-static method was overridden by a sub-class.

If you try to use a non-static method or variable from within a static method, you will receive one of the following errors at compile time.

  • non-static variable n cannot be referenced from a static context
  • non-static method nMethod() cannot be referenced from a static context

Static Variables
Static variables are variables whose value is shared by all instances of a class. Think of it as one value per class, not one value per instance. Static variables in a class are initialized before any object of that class can be created, and before any static method of the class runs. Static variables are instantiated once (and only once) when the class is loaded. The class is loaded when the JVM sees fit, you can tell the JVM when to load the class, but there is only a few instances where this might be desirable (I have not yet learned about them.) Typically the JVM loads a class because somebody is trying to make a new instance of a class, or use a static method or variable of the class.

When you call an operation on a static method or variable, you use the class name, not a reference. It is legal to call a static method using a reference variable, but the compiler just uses the reference to determine class type, and invokes the appropriate method without knowledge of the referenced object. This makes for less readable code. You can prevent a class from being instantiated by marking the constructor private.

Static Final Variables
Static final variables are constants. Declaring a variable as final means that once it is instantiated, the value cannot change. In the case of a static final variable, once the class is loaded, the variable is instantiated, value is assigned (implicitly to a default value if not explicitly), and is constant. There is no way to declare a variable as a constant, but there is a naming convention you can follow. Constant variables should be declared in all capital letters.

public static final int SECRETN = 7;

Tags: ,

Leave a Reply