1. 程式人生 > >Java static Data Initialization

Java static Data Initialization

Run the code first in your brain, then actually run the code to verify.

// housekeeping/StaticInitialization.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Specifying initial values in a class definition

class Bowl {
  Bowl(int marker) {
    System.out.println("Bowl(" + marker + ")");
  }

  void f1(int marker) {
    System.out.println("f1(" + marker + ")");
  }
}

class Table {
  static Bowl bowl1 = new Bowl(1);

  Table() {
    System.out.println("Table()");
    bowl2.f1(1);
  }

  void f2(int marker) {
    System.out.println("f2(" + marker + ")");
  }

  static Bowl bowl2 = new Bowl(2);
}

class Cupboard {
  Bowl bowl3 = new Bowl(3);
  static Bowl bowl4 = new Bowl(4);

  Cupboard() {
    System.out.println("Cupboard()");
    bowl4.f1(2);
  }

  void f3(int marker) {
    System.out.println("f3(" + marker + ")");
  }

  static Bowl bowl5 = new Bowl(5);
}

public class StaticInitialization {
  public static void main(String[] args) {
    System.out.println("main creating new Cupboard()");
    new Cupboard();
    System.out.println("main creating new Cupboard()");
    new Cupboard();
    table.f2(1);
    cupboard.f3(1);
  }

  static Table table = new Table(); // static member table
  static Cupboard cupboard = new Cupboard(); // static member cupboard
}

/* Output:
Bowl(1)
Bowl(2)
Table()
f1(1)

Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f1(2)

main creating new Cupboard()
Bowl(3)
Cupboard()
f1(2)

main creating new Cupboard()
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)
*/

Note that Cupboard creates a non- static Bowl bowl3 prior to the static definitions.

To summarize the process of creating an object, consider a class called Dog :

1. Even though it doesn’t explicitly use the static keyword, the constructor is actually a static method. So the first time you create an object of type Dog

, or the first time you access a static method or static field of class Dog , the Java interpreter must locate Dog.class , which it does by searching through the classpath.

2. As Dog.class is loaded (creating a Class object), all of its static initializers are run. Thus, static initialization takes place only once, as the Class

object is loaded for the first time.

3. When you create a new Dog() , the construction process for a Dog object first allocates enough storage for a Dog object on the heap.

4. This storage is wiped to zero, automatically setting all the primitives in that Dog object to their default values (zero for numbers and the equivalent for boolean and char ) and the references to null .

5. Any initializations that occur at the point of field definition are executed.

6. Constructors are executed. 

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/housekeeping/StaticInitialization.java