执行类的静态成员 - java

时间:2015-07-13 15:04:47

标签: java static-members

在理解类的静态成员时,它将根据它们在类上编写的顺序执行,例如:

class GelInk{

    static{
        System.out.println("First Static");
    }

    {
        System.out.println("Initialization block don't mind me");
    }

    static{
        System.out.println("Second Static");
    }

}

//Results to
First Static
Second Static
Initialization block don't mind me

但是当我尝试这段代码时:

class Ink{

        static{
            a=printStaticMessages(0);
        }
        static int a = printStaticMessages(1);

        Ink(){
            System.out.println(a);
        }

        static int printStaticMessages(int a){
            System.out.println("This is a static messages method " + a);
            return a;
        }
    }

它编译得很好,我预计会出现编译错误,因为静态块在被声明之前正在使用它。创建类的对象时,上面的代码会产生以下结果:

This is a static messages method 0
This is a static messages method 1
1

0 个答案:

没有答案