网站优化

网站优化

Products

当前位置:首页 > 网站优化 >

阅读Java静态代码块详解,能快速掌握静态代码块优化技巧吗?

GG网络技术分享 2025-11-13 13:15 1


根据给的文档内容, 我们Neng通过一个示例来展示父类和子类初始化的过程,并说明白静态成员变量和静态代码块先于实例成员施行的原因。

虚假设我们有一个父类Parent和一个子类Child,我们将在它们中分别定义静态成员变量和静态代码块。

java class Parent { static int parentCount = 0;

static {
    System.out.println;
    parentCount++;
}
Parent {
    System.out.println;
}

}

class Child extends Parent { static int childCount = 0;

static {
    System.out.println;
    childCount++;
}
Child {
    System.out.println;
}

public class Main { public static void main { System.out.println; Child child1 = new Child; Child child2 = new Child; System.out.println; System.out.println; } }

施行后来啊:

Parent static block Child static block In main Parent constructor Child constructor Parent constructor Child constructor Child count: 2 Parent count: 2

说明白:

  1. 当我们创建一个Child类的实例时JVM先说说加载Parent类和Child类。
  2. 在加载类时会先说说施行静态代码块。对于Parent类, 其静态代码块先说说施行,打印出“Parent static block”,并将parentCount设置为1。
  3. 接下来 JVM施行Child类的静态代码块,打印出“Child static block”,并将childCount设置为1。
  4. 接着,JVM调用构造方法来创建Child类的实例。个个实例在构造方法施行前会打印“Parent constructor”, 基本上原因是Child类继承了Parent类,且在构造方法中会隐式调用父类的无参构造方法。一边,会打印出“Child constructor”。
  5. 当我们施行System.out.println;System.out.println;时输出对应的静态变量值。

这玩意儿示例展示了静态成员变量和静态代码块在类加载和对象创建过程中的施行顺序。静态成员变量和静态代码块在类加载时施行,而实例成员变量和构造方法在对象创建时施行。

标签:

提交需求或反馈

Demand feedback