1.级联调用 ——构造器调用,示例代码:
output:
我是Animal类的构造器
我是Bird类的构造器
执行步骤:
1.执行new语句,进入Bird()
2.调用Animal(), 因为Animal是Bird的父类
3.调用Object(),因为Object是Animal的父类
4.返回Animal()
5.返回Bird()
6.End
调用了子类构造器会自动调用父类构造器,直至Object构造器,反应为编译器在子类构造器中自动首先添加super()
2.调用兄弟构造器
一旦通过this调用兄弟构造器,编译器不再自动添加super()(调用父类构造器),但调用兄弟的构造器时,其兄弟构造器调用了super(),其本质为推迟调用super(),
阅读(386) | 评论(2) | 转发(1) |
<script type=text/javascript charset=utf-8 src="http://static.bshare.cn/b/buttonLite.js#style=-1&uuid=&pophcol=3&lang=zh"></script> <script type=text/javascript charset=utf-8 src="http://static.bshare.cn/b/bshareC0.js"></script>
点击(此处)折叠或打开
- class Animal
- {
- public Animal ()
- {
- System.out.println("我是Animal类的构造器");
- }
- }
- //定义Bird继承自Animal类
- class Bird extends Animal
- {
- public Bird()
- {
- System.out.println("我是Bird类的构造器");
- }
- }
- public class Sample10_6
- {
- public static void main(String[] args)
- {
- new Bird();
- }
- }
我是Animal类的构造器
我是Bird类的构造器
执行步骤:
1.执行new语句,进入Bird()
2.调用Animal(), 因为Animal是Bird的父类
3.调用Object(),因为Object是Animal的父类
4.返回Animal()
5.返回Bird()
6.End
调用了子类构造器会自动调用父类构造器,直至Object构造器,反应为编译器在子类构造器中自动首先添加super()
2.调用兄弟构造器
点击(此处)折叠或打开
- class Animal
- {
- public Animal(String name)
- {
- //BlaBla....
- }
- public Animal()
- {
- //调用兄弟构造器
- this("tom");
- }
- }
- public class Sample10_12
- {
- public static void main(String[] args)
- {
- //创建对象
- new Animal();
- }
- }
一旦通过this调用兄弟构造器,编译器不再自动添加super()(调用父类构造器),但调用兄弟的构造器时,其兄弟构造器调用了super(),其本质为推迟调用super(),
相关热门文章
给主人留下些什么吧!~~
评论热议