【发布时间】:2011-11-02 15:13:25
【问题描述】:
考虑这段代码:
class Test {
Test() {
System.out.println("In constructor of Superclass");
}
int adds(int n1, int n2) {
return(n1+n2);
}
void print(int sum) {
System.out.println("the sums are " + sum);
}
}
class Test1 extends Test {
Test1(int n1, int n2) {
System.out.println("In constructor of Subclass");
int sum = this.adds(n1,n2);
this.print(sum);
}
public static void main(String[] args) {
Test1 a=new Test1(13,12);
Test c=new Test1(15,14);
}
}
如果我们在超类中有一个构造函数,它将被我们为子类构造的每个对象调用(例如,对象a 类Test1 调用Test1(int n1, int n2) 以及它的父类@987654325 @)。
为什么会这样?
这个程序的输出是:
在超类的构造函数中
在子类的构造函数中
总和是 25
在超类的构造函数中
在子类的构造函数中
总和是 29
【问题讨论】:
标签: java object constructor superclass