JAVA中static的执行顺序

static的特点:(它可以修饰成员变量,还可以修饰成员方法),不能修饰局部变量(即方法里的变量),会报错。

A:随着类的加载而加载
B:优先于对象存在
C:被类的所有对象共享
D:可以通过类名直接调用,当然,肯定也可以通过对象名调用

一般什么时候使用静态呢?
如果某个成员变量是被所有对象共享的,那么它就应该被定为静态的

static关键字注意事项
a、在静态方法中是没有this关键字的
b、静态方法只能访问静态的成员变量和静态的成员方法。

在JAVA中static的执行顺序

先看一个例子:

public class StaticDemo {

public static void main(String[] args) {

    System.out.println(Dog.name);
    Dog.shout();
    System.out.println();
    new Dog();

}

static {
    System.out.println("hello");
}

}

class Bell {
public Bell(int i) {
System.out.println(“bell ” + i + “: ding ling ding ling…”);
}
}

class Dog {

static Bell bell = new Bell(1);
static String name = "Bill";
static {
    System.out.println(name);
    System.out.println("static statement executed");
}

{
    System.out.println("normal statement executed");
}

static void shout() {
    System.out.println("a dog is shouting");
}

public Dog() {
    System.out.println("a new dog created");
}

Bell bell2 = new Bell(2);

}

执行结果

hello
bell 1: ding ling ding ling…
Bill
static statement executed
Bill
a dog is shouting

normal statement executed
bell 2: ding ling ding ling…
a new dog created

当StaticDemo.class加载到内存中时,随着class文件的加载,主函数所在的那个类将首先被执行(不管类在前在后)—>执行static{}的代码块—>执行main函数–>加载Dog类–>按顺序执行Dog类static修饰的变量—>加载bell类—>输出“bill”和”normal statement executed”—>调用Dog.name,Dog.shout()—>new Dog()—->之前已经被加载过Dog类,static修饰的变量只执行一次,之后的new Dog()都不会再去加载static修饰的变量—-》输出”normal statement executed”—-》成员变量比构造方法先执行,所以先执行Bell bell2 = new Bell(2)—》最后执行构造方法

在JAVA中static的执行顺序的原理总结

执行顺序:
static修饰的变量>成员变量>构造方法

注:{System.out.println(“hello”)},这样的代码块处于类中,方法外,也可看做是成员变量。

执行顺序详细

  1. 父类的 static 语句和 static 成员变量,同是static变量,按顺序执行

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

  3. 父类的 非 static 语句块和 非 static 成员变量
    {
    system.out.pringln(“2222”)
    }//这整个整体被当做成员变量

  4. 父类的构造方法

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

  6. 子类的构造方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值