initialization with inheritance

本文详细解析了Java中对象初始化的过程,包括静态成员和实例成员的初始化顺序,以及构造函数的执行流程。通过具体代码示例,展示了初始化过程中各部分的执行顺序,帮助读者深入理解Java对象创建的机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

After the necessary classes have all been loaded, so the object can be created. First, all the primitives in this object are set to their default values and the object references are set to null —this happens in one fell swoop by setting the memory in the object to binary zero. Then the base-class constructor is called.

All static objects and static code blocks are initialized in textual order (the order you write them in the class definition), at load time. The statics are initialized only once.

After the base-class constructor completes, the instance variables are initialized in textual order. Finally, the rest of the body of the constructor is executed.

// reuse/Beetle.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// The full process of initialization

class Insect {
  private int i = 9;
  protected int j;

  static {
    System.out.println("static code block.");
  }

  {
    System.out.println("normal code block.");
  }

  Insect() {
    System.out.println("i = " + i + ", j = " + j);
    j = 39;
  }

  private static int x1 = printInit("static Insect.x1 initialized");

  static int printInit(String s) {
    System.out.println(s);
    return 47;
  }
}

public class Beetle extends Insect {
  private int k = printInit("Beetle.k initialized");

  public Beetle() {
    System.out.println("k = " + k);
    System.out.println("j = " + j);
  }

  private static int x2 = printInit("static Beetle.x2 initialized");

  public static void main(String[] args) {
    System.out.println("Beetle constructor");
    // new Insect(); // [1]
    Beetle b = new Beetle(); // [2]
  }
}
/* My Output:
static code block.
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
normal code block.
i = 9, j = 0
Beetle.k initialized
k = 47
j = 39
*/
// when commented [2], uncommented [1], Output:
/*
static code block.
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
normal code block.
i = 9, j = 0
*/

for better understand, please read below content.

see instance initialization.

see static explicit data initialization.

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/reuse/Beetle.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值