UP | HOME

Static Field/Method, Initialization Block (Java)

package com.foo;
import org.apache.commons.lang.builder.ReflectionToStringBuilder; public class BaseObject { ** a static field; all object of this class share this variable. * private static long second = 0; private String name = ““; { System.out.println(”I am class block initialization.”); } static { System.out.println(“I am static block initialization.”); } public BaseObject() { super(); second++; System.out.println(“I am constructor.”); } public BaseObject(String name) { super(); this.name = name; second++; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static long getSecond() { return second; } public static void setSecond(long second) { BaseObject.second = second; } ?? (????) public String toString() { / jakarta lang toString utility return ReflectionToStringBuilder.toString(this); } public static void main(String[] args) { System.out.println(BaseObject.getSecond()); BaseObject bo1 = new BaseObject(“First One”); BaseObject bo2 = new BaseObject(“Seconde One”); BaseObject bo3 = new BaseObject(“Third One”); System.out.println(bo1 + ““ + BaseObject.getSecond()); System.out.println(bo2 + ”” + BaseObject.getSecond()); System.out.println(bo3 + “__” + BaseObject.getSecond()); } / expected result: * I am static block initialization. 0 I am class block initialization. I am class block initialization. I am class block initialization. com.foo.BaseObject@19821f[name=First One]_3 com.foo.BaseObject@190d11[name=Seconde One]_3 com.foo.BaseObject@a90653[name=Third One]_3 * }