Chinaunix首页 | 论坛 | 博客
  • 博客访问: 833015
  • 博文数量: 143
  • 博客积分: 455
  • 博客等级: 一等列兵
  • 技术积分: 861
  • 用 户 组: 普通用户
  • 注册时间: 2012-08-03 00:11
文章分类

全部博文(143)

文章存档

2018年(10)

2017年(6)

2016年(28)

2015年(14)

2014年(67)

2013年(1)

2012年(17)

我的朋友

分类: Android平台

2014-11-12 16:42:29

转载自:http://www.cppblog.com/ivy-jie/articles/85481.html
子类继承和调用父类的构造方法

1.如果子类没有定义构造方法,则调用父类的无参数的构造方法,.

2.如果子类定义了构造方法,不论是无参数还是带参数,在创建子类的对象的时候,首先执行父类无参数的构造方法,然后执行自己的构造方法。

3.如果子类调用父类带参数的构造方法,可以通过super(参数)调用所需要的父类的构造方法,切该语句做为子类构造方法中的第一条语句

4.如果某个构造方法调用类中的其他的构造方法,则可以用this(参数),切该语句放在构造方法的第一条.

说白了:原则就是,先调用父亲的.(没有就默认调,有了就按有的调,反正只要有一个就可以了.)

  1. package test;

  2. class Father{

  3. String s = "Run constructor method of Father";

  4. public Father(){

  5.    System.out.println(s);

  6. }

  7. public Father(String str){

  8.    s= str;

  9.    System.out.println(s);

  10. }

  11. }

  12. class Son extends Father{

  13. String s= "Run constructor method of son";

  14. public Son(){

  15.    //实际上在这里加上super(),和没加是一个样的

  16.    System.out.println(s);

  17. }

  18. public Son(String str){

  19.    this();//这里调用this()表示调用本类的Son(),因为Son()中有了一个super()了,所以这里不能再加了。

  20.    s = str;

  21.    System.out.println(s);

  22. }

  23. public Son(String str1, String str2){

  24.    super(str1+" "+str2);//因为这里已经调用了一个父类的带参数的super("---")了,所以不会再自动调用了无参数的了。

  25.    s = str1;

  26.    System.out.println(s);

  27. }

  28. }

  29. public class MyClass9 {

  30. public static void main(String[] args){

  31.    Father obfather1 = new Father();

  32.    Father obfather2 = new Father("Hello Father");

  33.    Son obson1 = new Son();

  34.    Son obson2 = new Son("hello son");

  35.    Son obson3 = new Son("hello son","hello father");

  36.   

  37. }

  38. }

===============

结果:

Run constructor method of Father

Hello Father

Run constructor method of Father

Run constructor method of son

Run constructor method of Father

Run constructor method of son

hello son

hello son hello father

hello son


阅读(4822) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~