这一小节我们主要讲解和初始化、赋值等相关的内容。
首先我们来看看静态代码块:
我们使用了一个Olive类存放数据:
package com.freesoft.testentity; public class Olive { public static final long BLACK = 0x000000; private String name; private long color = BLACK; public Olive(){ } public Olive(String name) { // 由于字段color已经被设置为默认值为BLACK,故这里无需再次设置 this.name = name; } public Olive(String name, int value) { super(); this.name = name; this.color = value; } @Override public String toString() { return "Olive [name=" + name + ", color=" + color + "]"; } }
package com.freesoft.testentity; import java.util.ArrayList; public class OliveJar { public static ArrayList<Olive> olives; static { System.out.println("Static Initialization"); // Java7新特性,可以无需填写new ArrayList<Olive>(); olives = new ArrayList<>(); olives.add(new Olive("Kalamata", 0x00FF00)); olives.add(new Olive("Picholine", 0xFF0000)); olives.add(new Olive("Kalamata", 0x0000FF)); } }
package com.freesoft.java7newfeature; import java.util.ArrayList; import com.freesoft.testentity.Olive; import com.freesoft.testentity.OliveJar; public class TestStatic { public static void main(String[] args) { System.out.println("Test main() method."); // 通过静态属性拿到List ArrayList<Olive> olives = OliveJar.olives; // for each loop for(Olive o: olives){ System.out.println(o); } } }
第二个例子我们看看实例代码块,我们修改一下OliveJar类:
package com.freesoft.testentity; import java.util.ArrayList; public class OliveJar { public ArrayList<Olive> olives; { System.out.println("Initializing"); // Java7新特性,可以无需填写new ArrayList<Olive>(); olives = new ArrayList<>(); olives.add(new Olive("Kalamata", 0x00FF00)); olives.add(new Olive("Picholine", 0xFF0000)); olives.add(new Olive("Kalamata", 0x0000FF)); } public OliveJar(){ System.out.println("OliveJar Constractor..."); } }
package com.freesoft.java7newfeature; import java.util.ArrayList; import com.freesoft.testentity.Olive; import com.freesoft.testentity.OliveJar; public class TestStatic { public static void main(String[] args) { System.out.println("Test main() method."); // 通过静态属性拿到List ArrayList<Olive> olives = new OliveJar().olives; // for each loop for(Olive o: olives){ System.out.println(o); } } }
对象的初始化顺序的主要原则:
总结:静态代码块内容先执行,接着执行父类非静态代码块和构造方法,然后执行子类非静态代码块和构造方法。
例子的话大家可以自己去实现。