2019.10.14java动手动脑

这次动手动脑,我学到了多个构造函数的顺序和相互调用,

 比如这个程序运行结果如下,由此我们知道,如果类里面自己定义了一个构造函数;系统将不会默认给出构造函数供主函数调用。

 1 package hello;
 2 
 3 public class Hello {
 4     public int value=200;
 5     {
 6         value =100;
 7     }
 8 
 9     public Hello() {
10         this.value = 300;
11     }
12 
13     public static void main(String[] args) {
14         Hello hello=new Hello();
15     System.out.println("初始化值为="+hello.value);
16 }
17 }

这是个初始化调用的问题,由运行结果我们可知道,系统会先调用构造函数,初始化数据。

3、

 1 class Root
 2 {
 3     static{
 4         System.out.println("Root的静态初始化块");
 5     }
 6     
 7     {
 8         System.out.println("Root的普通初始化块");
 9     }
10     public Root()
11     {
12         System.out.println("Root的无参数的构造器");
13     }
14 }
15 class Mid extends Root
16 {
17     static{
18         System.out.println("Mid的静态初始化块");
19     }
20     {
21         System.out.println("Mid的普通初始化块");
22     }
23     public Mid()
24     {
25         System.out.println("Mid的无参数的构造器");
26     }
27     public Mid(String msg)
28     {
29         //通过this调用同一类中重载的构造器
30         this();
31         System.out.println("Mid的带参数构造器,其参数值:" + msg);
32     }
33 }
34 class Leaf extends Mid
35 {
36     static{
37         System.out.println("Leaf的静态初始化块");
38     }
39     
40     {
41         System.out.println("Leaf的普通初始化块");
42     }
43     
44     public Leaf()
45     {
46         //通过super调用父类中有一个字符串参数的构造器
47         super("Java初始化顺序演示");
48         System.out.println("执行Leaf的构造器");
49     }
50 
51 }
52 
53 public class TestStaticInitializeBlock
54 {
55     public static void main(String[] args) 
56     {
57         new Leaf();
58         
59 
60     }
61 }

编译顺序是,在构建子类对象时,先构建父类的对象,之后一次执行相应的静态语句块,然后依次执行相应的普通语句块和构造函数,当在子类中有super();时,分类的构造函数使用super();调用的父类构造函数。

猜你喜欢

转载自www.cnblogs.com/mac-13/p/11696568.html