Java class 初始化和实例化练习

类的初始化 和 实例初始化的过程和练习.
摘要由CSDN通过智能技术生成

类初始化

初始化时机:

初始化是执行 class 或 interface 的初始化方法 <init>, 以下内容来自 JVM 文档 1 :

  • 当执行这些虚拟机指令时: new T, 存取 T 的静态变量/方法
  • new, 静态资源相关的 MethodHandle 实例被调用
  • 一些反射方法被调用. 例如 Class 的方法
  • T(T 是 class) 的子类被初始化
  • T(T 是 interface) 的实现类被初始化
  • T 是JVM启动时的初始化类

以下内容来自 Java 文档 2 :

  • T is a class and an instance of T is created.
  • A static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top level class (§7.6) and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

循环依赖:

package com.lvw.jvm.init_class;

public class CircleInitializing {
   

    public static void main(String[] args) {
   
        int f = Sub.f;
    }

    static class Super {
   
        static int f = 1;   // 1
        static {
     // 2
            System.out.println("Super is initializing.");
            Sub.run();  // 3
            System.out.println("Super was initialized.");
        }
        static void run() {
   
            System.out.println("Super.run() was called.");
        }
    }

    static class Sub extends Super {
    // 4 recursive ini
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值