java静态代码块、非静态代码块、构造方法和静态方法的执行顺序

1 静态代码块:有些代码必须在项目启动的时候就执行,这种代码是主动执行的(当类被载入时,静态代码块被执行,且只被执行一次,静态块常用来执行类属性的初始化)

2 静态方法:需要在项目启动的时候就初始化,在不创建对象的情况下,这种代码是被动执行的(静态方法在类加载的时候就已经加载 可以用类名直接调用)。

两者的区别是:静态代码块是自动执行的,

静态方法是被调用的时候才执行的.

静态代码块,在虚拟机加载类的时候就会加载执行,而且只执行一次;

非静态代码块,在创建对象的时候(即new一个对象的时候)执行,每次创建对象都会执行一次

不创建类执行静态方法并不会导致静态代码块或非静态代码块的执行。

不创建类执行静态方法并不会导致静态代码块或非静态代码块的执行,示例如下:

package com.practice.dynamicproxy;

class Parent {
    static String name = "hello";
    {
        System.out.println("parent block");
    }
    static {
        System.out.println("parent static block");
    }

    public Parent() {
        System.out.println("parent constructor");
    }
    
}

class Child extends Parent {
    static String childName = "hello";
    {
        System.out.println("child block");
    }
    static {
        System.out.println("child static block");
    }

    public Child() {
        System.out.println("child constructor");
    }
}

public class StaticIniBlockOrderTest {
    public static void test1() {
        System.out.println("static method");
    }
    public static void main(String[] args) {
//        new Child();// 语句(*)
//        new Child();
        StaticIniBlockOrderTest.test1();
    }
}

执行的结果如下:

static method

扫描二维码关注公众号,回复: 6617599 查看本文章

其余的示例代码如下:

package com.practice.dynamicproxy;

class Parent {
    static String name = "hello";
    {
        System.out.println("parent block");
    }
    static {
        System.out.println("parent static block");
    }

    public Parent() {
        System.out.println("parent constructor");
    }
    
}

class Child extends Parent {
    static String childName = "hello";
    {
        System.out.println("child block");
    }
    static {
        System.out.println("child static block");
    }

    public Child() {
        System.out.println("child constructor");
    }
}

public class StaticIniBlockOrderTest {
    public static void test1() {
        System.out.println("static method");
    }
    public static void main(String[] args) {
        new Child();// 语句(*)
        new Child();
//        StaticIniBlockOrderTest.test1();
    }
}

执行的结果如下:

parent static block
child static block
parent block
parent constructor
child block
child constructor
parent block
parent constructor
child block
child constructor

说明:静态代码块的只会执行一次,非静态代码块执行两次,先执行父类的非静态代码块和构造器,再执行本类的非静态代码块和构造器

猜你喜欢

转载自www.cnblogs.com/linwenbin/p/11084830.html