initialization with inheritance

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangbingfengf98/article/details/85309625

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

猜你喜欢

转载自blog.csdn.net/wangbingfengf98/article/details/85309625