Keyword static in Java

In this lesson, we will explore the static keyword in Java.

The keyword static can be applied to:

  • Attribute definition
  • Method definition
  • Code Block
  • Nested class

Static attributes

When placed in front of an attribute definition, it denotes an attribute that belongs to a class, not objects (as instances of a class).

Since the static fields are tied to the class itself and not to objects, no matter how many objects we create, there will always be only one version/value of the static variable.

Based on that, to access the static attribute of a class, we don’t need to instantiate it. We can access it with the class name.

Example

class Car {

  public static String MODEL = "Ford";
}

public class ConstructorExample {

  public static void main(String[] args) {

    System.out.println(Car.MODEL);
  }
}
Output: Ford

Static methods

The static method also belongs to the class and not objects. To call it, we use the class name. With static methods, we can access static data members of a class.

Example

class Car {

  public static String MODEL = "Ford";

  public static void printModel() {

    System.out.println("Model is: " + MODEL);
  }
}
Output: Model is: Ford
 
Read more about static methods: Java Instance and Static Methods.

Static block

A static code block is called a static Initializer. It gets executed only once when the class is loaded.

A class can have any number of static Initialization blocks that can appear anywhere in the class body. However, the runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

class ClassA {

  static Map <Double, String> map;

  static {
      map = new HashMap<Double, String>();
      map.put(7.2, "sampleValue");
      map.put(10.0, "sampleValue");
  }
   // rest of the code...
}

 

Static Nested Classes

As with class methods and variables, a static nested class is associated with its outer class. 

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

To create an object of static nested class, we use this syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();


To learn more, check out Java Tutorials for Beginners page. 

 

Leave a Reply

Your email address will not be published.