3 回答

TA貢獻1744條經(jīng)驗 獲得超4個贊
{ // Do Something...}
public class Test { static{ System.out.println("Static"); } { System.out.println("Non-static block"); } public static void main(String[] args) { Test t = new Test(); Test t2 = new Test(); }}
StaticNon-static blockNon-static block

TA貢獻1825條經(jīng)驗 獲得超4個贊
public class Foo { private static final int widgets; static { int first = Widgets.getFirstCount(); int second = Widgets.getSecondCount(); // Imagine more complex logic here which really used first/second widgets = first + second; }}
first
second
static
public class Foo { private static final int widgets = getWidgets(); static int getWidgets() { int first = Widgets.getFirstCount(); int second = Widgets.getSecondCount(); // Imagine more complex logic here which really used first/second return first + second; }}

TA貢獻1863條經(jīng)驗 獲得超2個贊
private static final HashMap<String, String> MAP = new HashMap<String, String>(); static { MAP.put("banana", "honey"); MAP.put("peanut butter", "jelly"); MAP.put("rice", "beans"); }
添加回答
舉報