A class that contains a static initializer:
class StaticInit
{
public static int x;
static
{
x = 32;
}
}
Initializing Data Members
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() {
}
}
Initialization order
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();
}
}
output
Tag(1)
Tag(2)
Tag(3)
Card()
Tag(33)
f()
Using Initialization Blocks:
A non-static initialization block
- Executed for each object that is created.
- Can initialize instance variables in a class.
|
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();
}
}
|
|
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.
|
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();
}
}
|
|
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 Mixed Initializer 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");
}
}
Explicit static initialization with the static clause 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)
}
}
Output
Inside main()
Cup(1)
Cup(2)
f(99) The full process of initialization
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();
}
}
output
|
|
static Insect.x1 initialized
static Beetle.x2 initialized
i = 1, j = 0
Beetle.k initialized
k = 0
j = 1 Demonstrates various initializers /*
* 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.com/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 <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
* @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 ########## */
Demonstrates the pitfalls of depending on the
order of static initializers /*
* 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.com/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 <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
* @version $Revision: 1.3 $
*/
public class StaticOrderDemo {
static {
Class cl = Values.class;
System.out.println("Class " + cl.getName() + " Loaded");
}
/**
* Creates a new instance of StaticOrderDemo
*/
public StaticOrderDemo() {
}
/**
* The main demo method. Used only to start the virtual machine.
*
* @param args Arguments passed.
*/
public static final void main(final String[] args) {
}
// --- Inner Classes --
/**
* Holds ranges for the values.
*
* @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
* @version $Revision: 1.3 $
*/
public static class Ranges {
/** Bluw range */
public static final String[] RANGE_BLUE = { "Sky", "Navy" };
/** Red range */
public static final String[] RANGE_RED = { "Light", "Dark" };
static {
System.out.println("static{} method for Ranges");
System.out.println(Arrays.asList(RANGE_BLUE));
System.out.println(Values.VALUE_SPECIFIER);
System.out.println(Arrays.asList(RANGE_RED));
}
}
/**
* Holds values.
*
* @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
* @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 ########## */
http://www.java2s.com/Tutorial/Java/0100__ Class-Definition/Catalog0100__Class-Definition.htm
|
|
|
No comments:
Post a Comment