块,静态块,子类,父类,继承加载顺序

来源:互联网 发布:狸窝视频剪辑软件下载 编辑:程序博客网 时间:2024/06/13 01:34
  1. class parent{
  2.     
  3.     
  4.     {
  5.     System.out.println("(parent)Loading the block...");
  6.     }
  7.     
  8.     static 
  9.     {
  10.         System.out.println("(parent)Loading the static block...");
  11.     }
  12.     
  13.     public parent()
  14.     {
  15.     System.out.println("(parent)Loading the construct...");
  16.     }
  17. }
  18. class child extends parent
  19. {
  20.     {
  21.             System.out.println("(child)Loading the block...");
  22.     }
  23.     
  24.     static 
  25.     {
  26.         System.out.println("(child)Loading the static block...");
  27.     }
  28.     
  29.     public child()
  30.     {
  31.             System.out.println("(child)Loading the construct...");
  32.     }
  33. }
  34. class load{
  35.     
  36.     public static void main(String ar[])
  37.     {
  38.         //new parent();
  39.         new child();
  40.     }
  41.     
  42. }

输出结果是:

(parent)Loading the static block...
(child)Loading the static block...
(parent)Loading the block...
(parent)Loading the construct...
(child)Loading the block...
(child)Loading the construct...

 

事实并非想象中:

(parent)Loading the static block...

(parent)Loading the block...

(parent)Loading the construct...
(child)Loading the static block...
(child)Loading the block...
(child)Loading the construct...

 

分析:

过程静态构造块>构造块>构造方法

由于继承是要先加载父类,再加载子类

而static 是与类中共存的所以一开始生成对象时,必先先执行静态方法,因此会先打印

(parent)Loading the static block...
(child)Loading the static block...

然后构造块是先构造方法,而子类中默认调用了super()方法,所以会打印

(parent)Loading the block...
(parent)Loading the construct...

最后打印

(child)Loading the block...
(child)Loading the construct...

分析到此,不知道理解有没错!

原创粉丝点击