在继承结构中,子类的构造方法会首先调用的父类的构造方法,然后执行本身的构造方法:
一、子类构造方法中没有使用super方法,则会默认调用父类方法无参数的构造方法,这时候父类中一定要实现无参的构造方法;
二、子类构造方法显示调用super方法,则会调用父类中对应参数的构造方法
测试类如下
父类BaseClass.java:
[img]http://dl.iteye.com/upload/attachment/352728/6f94af9d-e3cd-3d33-8ebd-5fb1d3214c0b.jpg[/img]
子类ChildClass.java:
[img]http://dl.iteye.com/upload/attachment/352730/dc77b65f-a77a-39b5-825e-110220f1eab6.jpg[/img]
客户端类InheritTest.java
[img]http://dl.iteye.com/upload/attachment/352732/f6f2127e-5a2d-35bd-9734-be90ddd79278.jpg[/img]
运行InheritTest.java之后输出为:
[color=red]父类的构造方法
子类构造
2[/color]
此时,如果BaseClass中没有无参的构造方法(public BaseClass(){}),则会报错,因为子类ChildClass中的构造方法(public ChildClass() {})默认调用的是父类无参的构造方法。
接下来对子类ChildClass进行如下修改:
[img]http://dl.iteye.com/upload/attachment/352734/6e5c2280-9b92-3809-85f4-8da7abd98ce8.jpg[/img]
增加了super(1)这行代码,
执行客户端类之后输出结果为:
[color=darkred]有参数父类的构造方法[/color]
[color=red]子类构造
2[/color]
super(1)的作用就是显式调用父类BaseClass中相对应参数的构造方法(public BaseClass(int i){}),此时BaseClass中无参的构造方法可有可无。
[color=orange]结论和原因[/color]:由此可以看出,子类在初始化时一定会先初始化父类,调用父类的构造函数,而调用哪个构造方法是通过super方法来确定(子类中没有显式调用super方法时则默认调用父类的无参构造方法),然后才初始化自身,调用自己的构造方法。究其原因,子类拥有父类的成员变量和成员方法,如果父类不初始化,则子类就不能正确调用这些变量和方法了。
一、子类构造方法中没有使用super方法,则会默认调用父类方法无参数的构造方法,这时候父类中一定要实现无参的构造方法;
二、子类构造方法显示调用super方法,则会调用父类中对应参数的构造方法
测试类如下
父类BaseClass.java:
[img]http://dl.iteye.com/upload/attachment/352728/6f94af9d-e3cd-3d33-8ebd-5fb1d3214c0b.jpg[/img]
子类ChildClass.java:
[img]http://dl.iteye.com/upload/attachment/352730/dc77b65f-a77a-39b5-825e-110220f1eab6.jpg[/img]
客户端类InheritTest.java
[img]http://dl.iteye.com/upload/attachment/352732/f6f2127e-5a2d-35bd-9734-be90ddd79278.jpg[/img]
运行InheritTest.java之后输出为:
[color=red]父类的构造方法
子类构造
2[/color]
此时,如果BaseClass中没有无参的构造方法(public BaseClass(){}),则会报错,因为子类ChildClass中的构造方法(public ChildClass() {})默认调用的是父类无参的构造方法。
接下来对子类ChildClass进行如下修改:
[img]http://dl.iteye.com/upload/attachment/352734/6e5c2280-9b92-3809-85f4-8da7abd98ce8.jpg[/img]
增加了super(1)这行代码,
执行客户端类之后输出结果为:
[color=darkred]有参数父类的构造方法[/color]
[color=red]子类构造
2[/color]
super(1)的作用就是显式调用父类BaseClass中相对应参数的构造方法(public BaseClass(int i){}),此时BaseClass中无参的构造方法可有可无。
[color=orange]结论和原因[/color]:由此可以看出,子类在初始化时一定会先初始化父类,调用父类的构造函数,而调用哪个构造方法是通过super方法来确定(子类中没有显式调用super方法时则默认调用父类的无参构造方法),然后才初始化自身,调用自己的构造方法。究其原因,子类拥有父类的成员变量和成员方法,如果父类不初始化,则子类就不能正确调用这些变量和方法了。