Java Tutorial/Class Definition/Initialization Block
Содержание
- 1 A class that contains a static initializer:
- 2 Demonstrates the pitfalls of depending on the order of static initializers
- 3 Demonstrates various initializers
- 4 Explicit static initialization with the static clause
- 5 Initialization order
- 6 Initializing Data Members
- 7 Mixed Initializer
- 8 The full process of initialization
- 9 Using Initialization Blocks: A non-static initialization block
- 10 Using Initialization Blocks: static initialization block
A class that contains a static initializer:
<source lang="java">
class StaticInit {
public static int x; static { x = 32; }
}</source>
Demonstrates the pitfalls of depending on the order of static initializers
<source lang="java">
/*
* file: StaticOrderDemo.java * package: oreilly.hcj.review * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. *
- DO NOT EDIT ABOVE THIS LINE ########## */
import java.util.Arrays; /**
* Demonstrates the pitfalls of depending on the order of static initializers. * * @author * @version $Revision: 1.3 $ */ public static class Values { /** A value holder */ public static final String VALUE = "Blue"; /** A specifier for the value */ public static final String VALUE_SPECIFIER; static { System.out.println("static{} method for Values"); System.out.println(VALUE); System.out.println(Ranges.RANGE_BLUE); VALUE_SPECIFIER = Ranges.RANGE_BLUE[1]; } }
} /* ########## End of File ########## */</source>
Demonstrates various initializers
<source lang="java">
/*
* file: InitializerDemo.java * package: oreilly.hcj.review * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. *
- DO NOT EDIT ABOVE THIS LINE ########## */
import java.util.StringTokenizer; /**
* Demonstrates various initializers. * * @author * @version $Revision: 1.4 $ */
public class InitializerDemo {
/** Simple static initialization. */ public static final String NAME = "Initializer Demo"; /** Initialized static on one line. */ public static final String ARCH = System.getProperty("os.arch"); /** Static method based initialization. */ public static final String USER_HOME; static { USER_HOME = System.getProperty("user.home"); } /** Simple instance member initialization. */ public String description = "An initialized member"; /** Method call instance member initialization. */ public long timestamp = System.currentTimeMillis(); /** Complex instance member initialization. */ private String xmlClasspath; { final StringBuffer buf = new StringBuffer(500); final String classPath = System.getProperty("java.class.path"); StringTokenizer tok = new StringTokenizer(classPath, System.getProperty("path.separator")); buf.append("<classpath>\n"); while (tok.hasMoreTokens()) { buf.append(" <pathelement location=\""); buf.append(tok.nextToken()); buf.append("\"/>\n"); } buf.append("</classpath>"); xmlClasspath = buf.toString(); } /** * Creates a new instance of Initalizers */ public InitializerDemo() { } /** * Main method of the demonstration. * * @param args Command line arguments (ignored). */ public static final void main(final String[] args) { InitializerDemo demo = new InitializerDemo(); System.out.println("------Dumping Contents-----------"); System.out.println("---------------------------------"); System.out.println(InitializerDemo.NAME); System.out.println(InitializerDemo.ARCH); System.out.println(InitializerDemo.USER_HOME); System.out.println(demo.description); System.out.println(demo.xmlClasspath); System.out.println("---------------------------------"); }
} /* ########## End of File ########## */</source>
Explicit static initialization with the static clause
<source lang="java">
class MyClass {
MyClass(int marker) { System.out.println("Cup(" + marker + ")"); } void f(int marker) { System.out.println("f(" + marker + ")"); }
} class MyStatic {
static MyClass c1; static MyClass c2; static { c1 = new MyClass(1); c2 = new MyClass(2); } MyStatic() { System.out.println("Cups()"); }
} public class MainClass {
public static void main(String[] args) { System.out.println("Inside main()"); MyStatic.c1.f(99); // (1) }
}</source>
Inside main() Cup(1) Cup(2) f(99)
Initialization order
<source lang="java">
class MyClass {
MyClass(int marker) { System.out.println("Tag(" + marker + ")"); }
} class MyInit {
MyClass t1 = new MyClass(1); // Before constructor MyInit() { System.out.println("Card()"); t3 = new MyClass(33); } MyClass t2 = new MyClass(2); // After constructor void f() { System.out.println("f()"); } MyClass t3 = new MyClass(3); // At end
} public class MainClass {
public static void main(String[] args) { MyInit t = new MyInit(); t.f(); }
}</source>
Tag(1) Tag(2) Tag(3) Card() Tag(33) f()
Initializing Data Members
<source lang="java">
public class MainClass {
static final double PI = 3.14; // Class variable that has a fixed value static int count = 0; // Class variable to count objects
public void aMethod() { }
}</source>
Mixed Initializer
<source lang="java">
public class MixedInitializer {
int i1; static int i2; int i3 = 2; static int i4 = 4; { System.out.println("i1 = " + i1); i1 = 6; System.out.println("i1 = 6"); } static { System.out.println("i2 = " + i2); i2 = 8; System.out.println("i2 = 8"); } public static void main(String[] args) { System.out.println("main() entered"); MixedInitializer mi = new MixedInitializer(); System.out.println("mi.i1 = " + mi.i1); System.out.println("i2 = " + i2); System.out.println("mi.i3 = " + mi.i3); System.out.println("i4 = " + i4); System.out.println("main() exited"); } { i1 += 6; System.out.println("6 + i1"); } static { i2 -= 3; System.out.println("i2 -= 3"); }
}</source>
The full process of initialization
<source lang="java">
class Insect {
private int i = 1; protected int j; Insect() { System.out.println("i = " + i + ", j = " + j); j = 1; } private static int x1 = print("static Insect.x1 initialized"); static int print(String s) { System.out.println(s); return 0; }
} class Beetle extends Insect {
private int k = print("Beetle.k initialized"); public Beetle() { System.out.println("k = " + k); System.out.println("j = " + j); } private static int x2 = print("static Beetle.x2 initialized");
} public class MainClass {
public static void main(String[] args) { Beetle b = new Beetle(); }
}</source>
static Insect.x1 initialized static Beetle.x2 initialized i = 1, j = 0 Beetle.k initialized k = 0 j = 1
Using Initialization Blocks: A non-static initialization block
- Executed for each object that is created.
- Can initialize instance variables in a class.
<source lang="java">
public class MainClass {
static int[] values = new int[10]; { System.out.println("Running initialization block."); for (int i = 0; i < values.length; i++) { values[i] = (int) (100.0 * Math.random()); } } void listValues() { for (int value : values) { System.out.println(value); } } public static void main(String[] args) { MainClass example = new MainClass(); System.out.println("\nFirst object:"); example.listValues(); example = new MainClass(); System.out.println("\nSecond object:"); example.listValues(); }
}</source>
Running initialization block. First object: 35 17 1 10 42 38 42 71 24 7 Running initialization block. Second object: 45 78 49 9 11 36 0 18 56 38
Using Initialization Blocks: static initialization block
- A block defined using the keyword static.
- Executed once when the class is loaded.
- Can initialize only static data members of the class.
<source lang="java">
public class MainClass {
static int[] values = new int[10]; static { System.out.println("Running initialization block."); for (int i = 0; i < values.length; i++) { values[i] = (int) (100.0 * Math.random()); } } void listValues() { for (int value : values) { System.out.println(value); } } public static void main(String[] args) { MainClass example = new MainClass(); System.out.println("\nFirst object:"); example.listValues(); example = new MainClass(); System.out.println("\nSecond object:"); example.listValues(); }
}</source>
Running initialization block. First object: 58 22 49 75 1 35 76 19 27 63 Second object: 58 22 49 75 1 35 76 19 27 63