子类对象初始化过程中构造函数调用的若干规则

来源:互联网 发布:java 返回值为泛型 编辑:程序博客网 时间:2024/06/05 03:15
1.如果父类中没有构造函数,即使用默认的构造函数,那子类的构造函数会自动调用父类的构造函数
[java] view plaincopy
  1. class Father  
  2. {  
  3.     private int a,b;  
  4.     void show()  
  5.     {  
  6.         System.out.println(a);  
  7.     }  
  8. }  
  9.   
  10. class Son extends Father  
  11. {  
  12.     private int c,d;  
  13.     Son(int c, int d)  
  14.     {  
  15.         this.c = c;  
  16.         this.d = d;     
  17.     }  
  18. }  
  19.   
  20. public class ConstructionTest  
  21. {  
  22.     public static void main(String args[])  
  23.     {  
  24.         Son s = new Son(23);  
  25.         s.show();  
  26.     }  
  27. }  
输出结果0,说明子类的构造函数自动调用父类的无参构造函数,初始化父类的成员为0

2.如果父类中定义了无参构造函数,子类的构造函数会自动调用父类的构造函数
[java] view plaincopy
  1. class Father  
  2. {  
  3.     private int a,b;  
  4.     Father(){System.out.println("father done");}  
  5.     void show()  
  6.     {  
  7.         System.out.println(a);  
  8.     }  
  9. }  
  10.   
  11. class Son extends Father  
  12. {  
  13.     private int c,d;  
  14.     Son(int c, int d)  
  15.     {  
  16.         this.c = c;  
  17.         this.d = d;     
  18.     }  
  19. }  
  20.   
  21. public class ConstructionTest  
  22. {  
  23.     public static void main(String args[])  
  24.     {  
  25.         Son s = new Son(23);  
  26.         s.show();  
  27.     }  
  28. }  
输出结果:father done
  0
说明重写了默认的无参构造函数,子类自动调用这个函数,父类的成员还是被初始化为0.

3. 如果定义了有参构造函数,则不会有默认无参构造函数,这样的话子类在调用父类的午餐构造函数的时候会出错(没有用super调用父类有参构造函数的情况下)
[java] view plaincopy
  1. //import java.io.*;  
  2.   
  3. class Father  
  4. {  
  5.     private int a,b;  
  6.     Father(int a, int b){this.a = a; this.b = b;}  
  7.     void show()  
  8.     {  
  9.         System.out.println(a);  
  10.     }  
  11. }  
  12.   
  13. class Son extends Father  
  14. {  
  15.     private int c,d;  
  16.     Son(int c, int d)  
  17.     {  
  18.         this.c = c;  
  19.         this.d = d;     
  20.     }  
  21. }  
  22.   
  23. public class ConstructionTest  
  24. {  
  25.     public static void main(String args[])  
  26.     {  
  27.         Son s = new Son(23);  
  28.         s.show();  
  29.     }  
  30. }  

输出结果:
Exception in thread "main" java.lang.NoSuchMethodError: Father: method <init>()V
not found
  at Son. <init>(Son.java:5)
  at ConstructionTest.main(ConstructionTest.java:6)
原创粉丝点击