1 package com.jdk7.chapter2.initorder;
2
3 public class Parent {
4 private int ix = 50;
//类变量
5 private static int iz = getNext(30);
//类的静态变量
6 //初始化代码块
7 {
8 System.out.println("Parent初始化代码块"
);
9 int x = 100
;
10 int y =
getNext(x);
11 }
12 //静态初始化代码块
13 static{
14 System.out.println("Parent静态初始化代码块"
);
15 int sx = 100
;
16 int sy =
getNext(sx);
17 }
18 public Parent(){
19 System.out.println("Parent构造函数"
);
20 }
21 public void display(){
22 System.out.println("Parent的display方法被调用"
);
23 System.out.println("ix = "+
this.ix);
24 displayA();
25 }
26
27 private static void displayA() {
28 System.out.println("Parent的displayA方法被调用"
);
29 }
30 private static int getNext(
int i) {
31 System.out.println("Parent的getNext被调用"
);
32 return 0
;
33 }
34 protected void finalize(){
35 System.out.println("Parent的销毁方法"
);
36 }
37 }
1 package com.jdk7.chapter2.initorder;
2
3 public class Child
extends Parent {
4 //初始化块
5 {
6 System.out.println("Child的初始化块"
);
7 }
8 //静态初始化块
9 static{
10 System.out.println("Child的静态初始化块"
);
11 }
12 public Child(){
13 super();
14 System.out.println("Child的构造函数"
);
15 }
16 public static void displayB(){
17 System.out.println("Child的displayB方法被调用"
);
18 }
19 public void finalize(){
20 System.out.println("Child的销毁方法被调用"
);
21 super.finalize();
22
23 }
24 }
1 package com.jdk7.chapter2.initorder;
2
3 public class InitOrderTest {
4 public static void main(String[] args) {
5 System.out.println("不new对象,访问静态方法的输出:"
);
6 Child.displayB();
7 System.out.println();
8
9 }
10 }
11
12 执行结果:
13 不new对象,访问静态方法的输出:
14 Parent的getNext被调用
15 Parent静态初始化代码块
16 Parent的getNext被调用
17 Child的静态初始化块
18 Child的displayB方法被调用
1 public class InitOrderTest {
2 public static void main(String[] args) {
3 System.out.println("new对象,访问静态方法的输出"
);
4 new Child().displayB();
5 System.gc();
6 }
7 }
8
9 执行结果:
10 new对象,访问静态方法的输出
11 Parent的getNext被调用
12 Parent静态初始化代码块
13 Parent的getNext被调用
14 Child的静态初始化块
15 Parent初始化代码块
16 Parent的getNext被调用
17 Parent构造函数
18 Child的初始化块
19 Child的构造函数
20 Child的displayB方法被调用
21 Child的销毁方法被调用
22 Parent的销毁方法
(1) 对于每个类,java虚拟机只加载一次,在加载时,初始化类的静态方法、静态变量、和静态初始化快;
(2) 只有在新建一个对象时,才会按先父类再子类的顺序,初始化类的初始化块和构造函数,若只访问静态方法,java虚拟即不会初始化这些块;
(3) System的gc方法通知java虚拟机进行垃圾回收,垃圾回收是异步的,回收时调用类的finalize方法
转载于:https://www.cnblogs.com/celine/p/8283360.html