Initialization and class loading

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Bruce Eckel’s Thinking in Java Contents | Prev | Next

class
loading

In
many more traditional languages, programs are loaded all at once as part of the
startup process. This is followed by initialization, and then the program
begins. The process of initialization in these languages must be carefully
controlled so that the order of initialization of
statics
doesn’t cause trouble. C++, for example, has problems if one
static
expects another
static
to
be valid before the second one has been initialized.

Java
doesn’t have this problem because it takes a different approach to
loading. Because everything in Java is an object, many activities become
easier, and this is one of them. As you will learn in the next chapter, the
code for each object exists in a separate file. That file isn’t loaded
until the code is needed. In general, you can say that until an object of that
class is constructed, the class code doesn’t get loaded. Since there can
be some subtleties with
static
methods, you can also say, “Class code is loaded at the point of first
use.”

Initialization
with inheritance

//: Beetle.java
// The full process of initialization.
 
class Insect {
  int i = 9;
  int j;
  Insect() {
    prt("i = " + i + ", j = " + j);
    j = 39;
  }
  static int x1 =
    prt("static Insect.x1 initialized");
  static int prt(String s) {
    System.out.println(s);
    return 47;
  }
}
 
public class Beetle extends Insect {
  int k = prt("Beetle.k initialized");
  Beetle() {
    prt("k = " + k);
    prt("j = " + j);
  }
  static int x2 =
    prt("static Beetle.x2 initialized");
  static int prt(String s) {
    System.out.println(s);
    return 63;
  }
  public static void main(String[] args) {
    prt("Beetle constructor");
    Beetle b = new Beetle();
  }
} ///:~ 

The
output for this program is:

static Insect.x initialized
static Beetle.x initialized
Beetle constructor
i = 9, j = 0
Beetle.k initialized
k = 63
j = 39

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read