一、Java构造函数的定义 构造函数(方法)注意几个特点: 1.函数名与类名相同 2.没返回、没有方法类型、也不能定义成void 3.程序自动调用、一个类可以定义多个构造函数,构造函数可以重载、以参数的个数,类型,或排列顺序区分 二、构造函数继承解析 现有以下几个类: |
public class Grandfather { public Grandfather(){ System.out.println("This is Grandfather!"); } public Grandfather(String s){ System.out.println("This is Grandfather"+s); } } public class Father extends Grandfather { public Father(){ System.out.println("This is Father!"); } public Father(String s){ System.out.println("This is Father!"+s); } } public class Son extends Father { public Son(){ System.out.println("This is Son!"); } public Son(String s){ System.out.println("This is Son"+s); } } public class Construct { /** * @param args */ public static void main(String[] args) { Son son = new Son(); System.out.println("**********************************"); Son son1 = new Son("**==**"); } }
执行结果:
This is Grandfather!
This is Father!
This is Son!
**********************************
This is Grandfather!
This is Father!
This is Son**==**
从控制台打印的结果可以看出,当执行子类时,都是去找它的父类的缺省的构造函数,先执行父类的构造函数,再执行子类的本身。
针对以上情况,我们现在做个修改,改其中的一个类的代码如下:把Grandfather类显式写出的缺省构造函数注释掉
public class Grandfather { // public Grandfather(){ // System.out.println("This is Grandfather!"); // } // public Grandfather(String s){ System.out.println("This is Grandfather"+s); } }
如果你用的是IDE开发工具,可以很快的就发现,继承这个Grandfather类的Father类,就已经报错了
我们就得出结论:
如果不指定的情况下,子类有多个构造函数的时候,父类要嘛没有构造函数,要嘛最少有一个显式写出的缺省构造函数供子类构造函数调用.
如果要指定子类调用父类的某个构造函数,则要把代码改写如下:
public class Father extends Grandfather { public Father(){ super("**ss**"); System.out.println("This is Father!"); } public Father(String s){ super(s); System.out.println("This is Father!"+s); } }
这样就指定了,作为子类的Father类,指定了调用父类Grandfather类的Grandfather(String s)构造函数
执行Construct.java
控制台输出为:
This is Grandfather**ss**
This is Father!
This is Son!
**********************************
This is Grandfather**ss**
This is Father!
This is Son**==**