码迷,mamicode.com
首页 > 编程语言 > 详细

java静态初始化代码块

时间:2015-08-12 00:58:24      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

/*
 * 为什么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 + ")";
    }
}

  

java静态初始化代码块

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!