java静态初始化代码块

/*
 * 为什么Java中为什么没有静态构造函数。其实Java中不叫静态构造函数,称作静态初始化,或者静态代码块。
 * 可以通过这样的代码实现相同的功能:
 */
public class test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(Point.getValue());
        System.out.println(new Point());  //why?不直接调用方法即可呢
    }
}

class Point {
    private static int value = 0;

    public static int getValue() {
        return value;
    }
    //静态代码块*1
    static {
        value++;
    }
   //静态代码块*2
    static {
        value++;
    }

    private int x = 0;
    private int y = 0;

    {
        this.x = 10;
    }

    {
        this.y = 10;
    }

    public String toString() {
        return "(x:" + this.x + ",y:" + this.y + ")";
    }
}

  

原文地址:https://www.cnblogs.com/shuqingstudy/p/4722678.html