Java 构造函数中的super()

来源:互联网 发布:苹果电脑安装网页软件 编辑:程序博客网 时间:2024/06/01 09:26
public class Test {      public static void main(String[] args) {          new Son("baidu");          new Son();      }  }  class Farther{      public Farther(){          System.out.println("I am father");      }      public Farther(String name){          System.out.println("I am father:"+name);      }  }  class Son extends Farther{      public Son(){          System.out.println("I am son");      }      public Son(String name){          //super("google");          System.out.println("I am son:"+name);      }  }  

Java在实例化一个对象的时候,如果没有显式使用super(),则会先调用父类的无参构造函数(不是和自己构造函数参数数量对应的那个),然后调用子类的构造函数,如果父类不是Object类,则一直向上追溯到Object类为止,super()只能在构造函数的第一行使用,在别的地方使用均为非法,一般情况下构造函数不用写super(),但是如果一个类有多个构造函数的时候,为了便于理解,往往要显式调用super()。
上面代码的运行结果为:

I am fatherI am son:baiduI am fatherI am son
0 0
原创粉丝点击