Java/Class/Static
Содержание
Explicit static initialization with the static clause
<source lang="java">
// : c04:ExplicitStatic.java // Explicit static initialization with the "static" clause. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. class Cup {
Cup(int marker) { System.out.println("Cup(" + marker + ")"); } void f(int marker) { System.out.println("f(" + marker + ")"); }
} class Cups {
static Cup c1; static Cup c2; static { c1 = new Cup(1); c2 = new Cup(2); } Cups() { System.out.println("Cups()"); }
} public class ExplicitStatic {
public static void main(String[] args) { System.out.println("Inside main()"); Cups.c1.f(99); // (1) } // static Cups x = new Cups(); // (2) // static Cups y = new Cups(); // (2)
} ///:~
</source>
Java static member variable example
<source lang="java">
public class Main {
public static void main(String[] args) { Counter object1 = new Counter(); System.out.println(object1.getNumberOfObjects()); Counter object2 = new Counter(); System.out.println(object2.getNumberOfObjects()); }
} class Counter {
static int counter = 0; public Counter() { counter++; } public int getNumberOfObjects() { return counter; }
}
</source>
Java static method
<source lang="java">
public class Main {
public static void main(String[] args) { int result = add(1, 2); System.out.println("(1+2) is : " + result); } public static int add(int first, int second) { return first + second; }
} //(1+2) is : 3
</source>
Show that you can"t have static variables in a method
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
/**
* Show that you can"t have static variables in a method, unlike C/C++ */
public class NoLocalStatics {
public static void main(String[] argv) { NoLocalStatics t = new NoLocalStatics(); t.process(); } void process() { static int a = 42; // EXPECT COMPILE ERROR System.out.println("Process: " + a); }
}
</source>
Show that you do inherit static fields
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
// Show that you do inherit static fields. /** This is the class that we extend. */ class AnOtherClass {
AnOtherClass() { System.out.println("In AnOtherClass::<init>"); } static int foo = 24; static int bar() { return 42; }
} /** This is the subclass */ public class InheritStatics extends AnOtherClass {
public static void main(String[] c) { new InheritStatics().run(); } public void run() { System.out.println("In InheritStatics::run"); System.out.println("Foo is " + foo); System.out.println("Bar is " + bar()); }
}
</source>
Static field, constructor and exception
<source lang="java">
public class Main {
static Bar bar; static { try { bar = new Bar(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] argv) { System.out.println(bar); }
} class Bar {
public Bar() throws Exception { } public String toString() { return "Bar"; }
}
</source>
Static Init Demo
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
/**
* Show static initializers. These are run when the class is loaded. * If you run the main program here, you will see the static * initializer before the "About to load class", since the class * is loaded before main gets run. If you copy the guts of main into * another class, the messages will come out in the "expected" order. * * @author Ian F. Darwin, http://www.darwinsys.ru/ * @version $Id: StaticIniDemo.java,v 1.5 2004/02/09 03:33:54 ian Exp $ */
public class StaticIniDemo {
/** A static initializer - called when class is loaded. */ static { System.out.println("In static initializer"); } /** A constructor -- called when object is instantiated. */ public StaticIniDemo() { System.out.println("In Constructor"); } public static void main(String[] a) { try { System.err.println("About to load class"); Class c = Class.forName("StaticIniDemo"); System.err.println("About to construct instance"); Object sd = c.newInstance(); System.err.println("Object is " + sd); } catch (Exception e) { e.printStackTrace(); } }
}
</source>
Using Static Variables
<source lang="java">
/* In this example, the Box class contains a static variable, numBoxes, which is incremented each time a Box object is created. The main() method of the TestStaticVar class creates two Box objects, then prints out the value of the static variable.
- /
class Box {
double width; public static int numBoxes = 0; // static variable is declared and initialized public Box() { width = 5.0; numBoxes++; // numBoxes is incremented to count number of objects. }
}
public class TestStaticVar {
public static void main (String args[]) { Box box1 = new Box(); Box box2 = new Box(); System.out.println("Number of objects = " + Box.numBoxes); }
}
</source>