关于java初始化顺序的一个示例
  ApTxpH0CpnLS 2023年11月02日 50 0
public 
    
  class 
   Sample
{
     
  public 
    
  static 
    
  void 
   main(String[] args){
        B ba  
  = 
    
  new 
   B();
        
        System.out.println( 
  " 
  ------------------------------- 
  " 
  );

        B bb  
  = 
    
  new 
   B();
    }
};


 
  class 
   Target
{
     
  public 
   Target(String s){
        System.out.println( 
  " 
  Target( 
  " 
  + 
  s 
  + 
  " 
  ) 
  " 
  );
    }
};

 
  class 
   A
{
    
     
  public 
    
  static 
   Target td  
  = 
    
  new 
   Target( 
  " 
  static in A 
  " 
  );
     
  static 
  {
        System.out.println( 
  " 
  static block in A 
  " 
  );
    }

    {
        System.out.println( 
  " 
  non-static block in A 
  " 
  );
    }

     
  public 
   Target ta  
  = 
    
  new 
   Target( 
  " 
  in A 
  " 
  );
};

 
  class 
   B  
  extends 
   A
{
     
  public 
   Target tb  
  = 
    
  new 
   Target( 
  " 
  in B 
  " 
  );
     
  static 
  {
        System.out.println( 
  " 
  static block in B 
  " 
  );
    }
     
  static 
    
  public 
   Target tc  
  = 
    
  new 
   Target( 
  " 
  static in B 
  " 
  );

    {
        System.out.println( 
  " 
  non-static block in B 
  " 
  );
    }
    
};




结果:

Target( static   in  A)
static  block  in  A
static  block  in  B
Target( static   in  B)
non - static  block  in  A
Target( in  A)
Target( in  B)
non - static  block  in  B
-------------------------------
non - static  block  in  A
Target( in  A)
Target( in  B)
non - static  block  in  B





注意:


  1. All data fields are initialized to their default value (0, false, or null).
  2. All field initializers and initialization blocks are executed, in the order in which they occur in the class declaration.
  3. If the first line of the constructor calls a second constructor, then the body of the second constructor is executed.
  4. The body of the constructor is executed。


另外,可以看到:


先父类的static,后子类的static,然后父类的非static,再子类的非static。


static包括静态的字段和初始化块。


非static包括非静态字段和初始化块。


同级别的字段或初始化块的顺序就依赖于定义的先后了。



还有一点简单的,顺便提一下:


static的东东只在类装入的时候,执行一次。不是每次实例化一个对象时都执行。



顺便提第二点:在jdk5中因为支持可变参数列表所以,




关于java初始化顺序的一个示例_string

public

  static   void  main(String... args) ... {}


是成立的。



另外,关于初始化问题参见:


http://www.javaworld.com/javaworld/jw-03-1998/jw-03-initialization.html?page=1

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  D04qQxYJZ4A6   2023年11月19日   24   0   0 mysqljava读写分离
  bYdMetjCLs2g   2023年11月19日   23   0   0 tomcatjava
  UP4ONKOBnkdD   2023年11月28日   24   0   0 java
  9JCEeX0Eg8g4   2023年12月10日   30   0   0 应用程序javaApache
  P3nxyT0LRuwj   2023年11月19日   26   0   0 javawar包jar
  KRsXEGSB49bk   2023年11月27日   29   0   0 javaApache
  xwGmYGXf1w4S   2023年11月22日   43   0   0 tomcatjavaApache