子类继承了父类,子类就拥有父类的成员变量和方法。子类实例化时首先为父类定义的成员变量分配和初始化。这就需要调用父类的构造方法。 默认是调用父类的默认构造方法,如果父类没有无参的构造方法,就需要在子类的构造方法中显示地调用父类的构造方法,并且放在构造方法的第一语句。 否则发生编译错误。
下例中,子类的构造方法Soun(int a,int b,int c)在第一语句就调用父类Father(int a,int b)构造方法,调用父类构造方法使用关键字super。 如果不这样做将隐式调用默认父类默认构造方法,而本例的Father类并没有提供,将会报编译错误。
class Father { int a; int b; public Father(int a,int b){ this.a=a; this.b=b; } public void printLine(){ System.out.println("------------"); } public void printValue(){ System.out.println("a="+a+"\tb="+b); } } class Son extends Father{ int c; public Son(int a,int b,int c){ super(a,b); this.c=c; } public void printValue(){ System.out.println("a="+a+"\tb="+b+"\tc="+c); } public void printStar(){ System.out.println("************"); } } public class Demo1 { public static void main(String[] args) { Son son=new Son(1,2,3); son.printLine(); son.printStar(); son.printValue(); } } |
运行程序,结果如下图所示: