我记得那时候刚毕业。学习JAVA恐惧是这里,它是关于JAVA称号。我总是不正确。如今,这最后审查。看了好半天。得赶紧把刚才学习到的那点东西记下来。
一、关于static的代码段运行顺序
package com.test; /** * Created with IntelliJ IDEA. * User: 菜鸟大明 * Date: 14-6-15 * Time: 下午11:19 * To change this template use File | Settings | File Templates. */ class Mug { Mug(int marker) { System.out.println("Mug(" + marker + ")"); } void f(int marker) { System.out.println("f(" + marker + ")"); } } public class Mugs { Mug c1; Mug c2; { c1 = new Mug(1); c2 = new Mug(2); System.out.println("c1 & c2 initialized"); } Mugs() { System.out.println("Mugs()"); } public static void main(String[] args) { System.out.println("Inside main()"); Mugs x = new Mugs(); Mugs y = new Mugs(); } } |
来自CODE的代码片
snippet_file_0.txt
运行结果例如以下:
Inside main()
Mug(1)
Mug(2)
c1 & c2 initialized
Mugs()
Mug(1)
Mug(2)
c1 & c2 initialized
Mugs()
二、关于非static得代码段运行顺序
package com.test; /** * Created with IntelliJ IDEA. * User: 菜鸟大明 * Date: 14-6-15 * Time: 下午11:21 * To change this template use File | Settings | File Templates. */ 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()"); } } class ExplicitStatic { public static void main(String[] args) { System.out.println("Inside main()"); Cups.c1.f(99); // (1) } // 先初始化静态变量 static Cups x = new Cups(); // (2) // 第二次初始化静态变量Cups static Cups y = new Cups(); // (2) } |
来自CODE的代码片
snippet_file_0.txt
运行结果例如以下:
Cup(1)
Cup(2)
Cups()
Cups()
Inside main()
f(99)
结论:这里面涉及到的知识非常多,有代码块、匿名内部类、static初始化等等,用这么一个大样例我感觉基本能说清楚了。
须要提一下就是关于static变量、方法、代码块的初始化仅仅有一次,也就是当类第一次被调用的时候执行初始化。以后不管此类再被new多少次,均不再执行初始化。