看代码
- class StaticTest1 {
- static int i = 47;
- }
- class Incrementable1 {
- static void increment() {
- StaticTest1.i++;
- }
- }
- public class OneStaticTest {
- @SuppressWarnings("static-access")
- public static void main(String[] args) {
- System.out.println("StaticTest1.i= " + StaticTest1.i);
- StaticTest1 st1 = new StaticTest1();
- StaticTest1 st2 = new StaticTest1();
- System.out.println("st1.i= " + st1.i);
- System.out.println("st2.i= " + st2.i);
- Incrementable1.increment();
- System.out.println("After Incrementable.increment() called: ");
- System.out.println("st1.i = " + st1.i);
- System.out.println("st2.i = " + st2.i);
- Incrementable1.increment();
- System.out.println("After Incrementable.increment called: ");
- System.out.println("st1.i = " + st1.i);
- System.out.println("st2.i = " + st2.i);
- st1.i = 3;
- System.out.println("After st1.i = 3, ");
- System.out.println("st1.i = " + st1.i);
- System.out.println("st2.i = " + st2.i);
- System.out.println("Create another StaticTest, st3.");
- /*
- * 一个static字段对每个类来说只有一份存储空间
- * 非static字段则是对每个对象有一个存储空间
- */
- StaticTest1 st3 = new StaticTest1();
- System.out.println("st3.i = " + st3.i);
- }
- }
输出结果:
- StaticTest1.i= 47
- st1.i= 47
- st2.i= 47
- After Incrementable.increment() called:
- st1.i = 48
- st2.i = 48
- After Incrementable.increment called:
- st1.i = 49
- st2.i = 49
- After st1.i = 3,
- st1.i = 3
- st2.i = 3
- Create another StaticTest, st3.
- st3.i = 3
由上边可以看出,当用static创建了一个静态域之后,它只和类有关系,即static域只有一个实例,与创建了多少个对象无关。
再看下边代码:
- class Cup {
- Cup(int marker) {
- print("Cup(" + marker + ")");
- }
- void f(int marker) {
- print("f(" + marker + ")");
- }
- }
- class Cups {
- static Cup cup1;
- static Cup cup2;
- static {
- cup1 = new Cup(1);
- cup2 = new Cup(2);
- }
- Cups() {
- print("Cups()");
- }
- }
- public class ExplicitStatic {
- public static void main(String[] args) {
- print("Inside main()");
- Cups.cup1.f(99); // (1)
- }
- //先执行静态构造块,再执行构造函数。而且构造块只执行一次。
- static Cups cups1 = new Cups(); // (2)
- static Cups cups2 = new Cups(); // (2)
- }
输出:
Cup(1)
Cup(2)
Cups()
Cups()
Inside main()
f(99)