java 继承时候类的执行顺序问题
java 继承时候类的执行顺序问题
子类在继承父类后,创建子类对象会首先调用父类的构造函数,先执行父类的构造函数,然后再执行子类的构造函数,如下所示:
1 class Father{ 2 public Father(){ 3 System.out.println("I am father"); 4 } 5 } 6 public class Child extends Father{ 7 public Child(){ 8 System.out.println("I am child"); 9 } 10 public static void main(String[] args) { 11 Father f=new Father(); 12 Child c=new Child(); 13 } 14 }
当父类有带参数的构造函数时,子类默认是调用不带参数的构造函数,如下所示:
1 class Father{ 2 public Father(){ 3 System.out.println("I am father"); 4 } 5 public Father(String name){ 6 System.out.println("I am father,My name is "+name); 7 } 8 } 9 public class Child extends Father{ 10 public Child(){ 11 System.out.println("I am child"); 12 } 13 public static void main(String[] args) { 14 Father f=new Father("Apache"); 15 Child c=new Child(); 16 } 17 }
若想子类调用父类带参数的构造函数,需要用super()函数申明,如下:
1 class Father{ 2 public Father(){ 3 System.out.println("I am father"); 4 } 5 public Father(String name){ 6 System.out.println("I am father,My name is "+name); 7 } 8 } 9 public class Child extends Father{ 10 public Child(){ 11 super("Apache"); 12 System.out.println("I am child"); 13 } 14 public static void main(String[] args) { 15 Father f=new Father("Apache"); 16 Child c=new Child(); 17 } 18 }