![]() ![]() ![]() |
INPRISE Online And ZD Journals Present:
When you create an object of a given class, several things must happen, in a specific order, to ensure that the object is ready for use. Some of this work is the responsibility of the constructor, but there are also rules that define how the program will initialize other program values. In particular, Java programs must conform to rules for initializing static and non-static data in order to ensure that the program will behave consistently. Declaration of
initialization
If you declare more than one static field in your class, the program will initialize them in declaration order. Similarly, it will initialize non-static fields in declaration order. Unless you specify otherwise, a Java program initializes boolean fields to False, char fields to null, and all numeric fields to zero. To specify a different initial value, you simply assign the value as part of the declaration statement, like this: MyClass a = new MyClass(); You can even call methods to return an initialization value. For static fields, the syntax is the same, but the code executes only upon the first use of the class (to create an object, or to reference any static field or method). At this point, you may wonder why you’d use a constructor instead of simply using static and non-static initialization statements. The answer lies in what you can’t do with these statements—call methods that don’t return initialization values, set fields to values computed at runtime, and so on. However, before the body of the constructor executes, all fields will be initialized to a value, either default or user-supplied. If you want to control the order of initialization of the static fields, you’ll create a static initialization block. This looks like a normal method block, but has no method name—only the static label, as below: static { b = 2; a = b; c = new MyClass(); } This appears a bit odd, but it works and executes upon the first use of the class, as when you initialize the static fields individually. In a similar fashion, Java 1.1 allows you to specify an initialization block for non-static fields. The syntax is simply a block with no method name, as below: class MyNewClass { int a; int b; MyClass c; { b = 2; a = b; c = new MyClass(); } //... } This syntax is necessary for initializing anonymous inner classes. Tim Gooch is editor-in-chief of JBuilder Developer's Journal as well as several other ZD Journals publications. Back to Top Back to Index of Articles Copyright © 1997, ZD Journals, a division of Ziff-Davis Inc. ZD Journals and ZD Jounals logo are trademarks of Ziff-Davis Inc. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of Ziff-Davis is prohibited. |