看如下程序

 1 class A {
 2    static{
 3       System.out.println("A static");
 4    }   
 5 
 6    {
 7       System.out.println("A not static"); 
 8    }   
 9 
10    public A(){
11       System.out.println("A new");
12    }
13 }
14 
15 class B extends A{
16    static{
17       System.out.println("B static");
18    }   
19 
20    {
21       System.out.println("B not static"); 
22    }  
23 
24    public B(){
25       System.out.println("B new");
26    }
27 } 
28 
29 public class MainTest {
30    public static void main(String[] args) {
31       A ab= new B();
32       ab= new B();
33    }
34 }

输出如下:

A static

B static

A not static

A new

B not static

B new

A not static

A new

B not static

B new

 

结论: 

静态代码块只有类首次加载进内存时调用一次,只此一次。

非静态代码块,每次创建对象时,会在构造函数之前被调用。

构造函数,每次创建对象时,最后调用。

创建子类对象时,先创建父类对象,再创建子类对象。

相关文章:

  • 2021-06-13
  • 2022-12-23
  • 2021-10-01
  • 2021-08-25
  • 2021-07-15
  • 2021-12-09
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-04-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案