示例一

 1 class Grandparent {
 2 
 3     public Grandparent() {
 4         System.out.println("GrandParent Created.");
 5     }
 6 
 7     public Grandparent(String string) {
 8         System.out.println("GrandParent Created.String:" + string);
 9     }
10 }
11 
12 class Parent extends Grandparent {
13 
14     public Parent() {
15         //super("Hello.Grandparent.");
16         System.out.println("Parent Created");
17        //super("Hello.Grandparent.");
18     }
19 }
20 
21 class Child extends Parent {
22 
23     public Child() {
24         System.out.println("Child Created");
25     }
26 }
27 
28 public class TestInherits {
29 
30     public static void main(String args[]) {
31         Child c = new Child();
32     }
33 }

结果截图

去掉第15行注释符后

 分析:通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。否则将出现编译错误。在该程序中,Parent类继承了Grandparent类,Child类又继承了Parent类,由于super位于Parent类中,调用其基类Grandparent的构造函数,由于super("Hello.Grandparent.")带有参数,调用的是第二个构造函数。

  子类的初始化会造成父类构造函数的执行。

posted on 2015-11-04 17:40  卫平公  阅读(205)  评论(0)    收藏  举报