您的位置:首页 > 编程语言 > Java开发

java static用法

2016-03-09 13:03 387 查看
Java中的静态(static)关键字只能用于成员变量或语句块,以及静态方法。其中成员变量,语句块在类加载时会自动执行,即主动执行,不需要通过对象来执行。静态方法不需要通过对象来调用,没有其他方法调用时不会被执行,属于被动执行。

执行顺序

static 语句的执行时机实在第一次加载类信息的时候(如调用类的静态方法,访问静态成员,或者调用构造函数), static 语句和 static 成员变量的初始化会先于其他语句执行,而且只会在加载类信息的时候执行一次,以后再访问该类或new新对象都不会执行

而非 static 语句或成员变量,其执行顺序在static语句执行之后,而在构造方法执行之前,总的来说他们的顺序如下

1. 父类的 static 语句和 static 成员变量

2. 子类的 static 语句和 static 成员变量

3. 父类的 非 static 语句块和 非 static 成员变量

4. 父类的构造方法

5. 子类的 非 static 语句块和 非 static 成员变量

6. 子类的构造方法

例子1:

package myProj;

public class StaticTest {

    

    public static void main(String[] args){

                 

        staticFunection();           

    }

     

    static StaticTest st = new StaticTest();

     

    static{

        System.out.println("1");

    }

     

    {

        System.out.println("2");

    }

     

    public StaticTest() {

        // TODO Auto-generated constructor stub

        System.out.println("3");

        System.out.println("a ="+ a +", b="+b);

    }

     

    public static void staticFunection(){

        System.out.println("4");

    }

     

    int a = 110;

    static int b = 112;

}

【输出】

2

3

a =110, b=0

1

4

例子2:

新增class

package myProj;

public class StaticTest1 {
static {
System.out.println("this is static of parent class");
}
{
System.out.println("this is not static of parent class");
}
public
StaticTest1 (){
System.out.println("this is parent class");
}

}

修改StaticTest

//static StaticTest st = new StaticTest();

static
StaticTest1 st = new StaticTest1();

static
StaticTest1 st1 = new StaticTest1();

【输出结果】

this is static of parent class

this is not static of parent class

this is parent class

this is not static of parent class

this is parent class

1

4

其中静态代码块只被执行了一次
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java static