为什么在声明子类的对象时会调用超类的构造函数?(爪哇) [英] Why is constructor of super class invoked when we declare the object of sub class? (Java)
本文介绍了为什么在声明子类的对象时会调用超类的构造函数?(爪哇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑这个代码:
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);
}
}
如果我们在超类中有一个构造函数,它会被我们为子类构造的每个对象调用(例如,Test1
类的对象a
调用Test1(int n1, int n2)
及其父 Test()
).
If we have a constructor in super class, it will be invoked by every object that we construct for the child class (ex. Object a
for class Test1
calls Test1(int n1, int n2)
and as well as its parent Test()
).
为什么会发生这种情况?
Why does this happen?
这个程序的输出是:
在超类的构造函数中
在子类的构造函数中
总和是 25
在超类的构造函数中
在子类的构造函数中
总和是 29
推荐答案
因为它将确保在调用构造函数时,它可以依赖其超类中正在初始化的所有字段.
Because it will ensure that when a constructor is invoked, it can rely on all the fields in its superclass being initialised.
请参阅此处
这篇关于为什么在声明子类的对象时会调用超类的构造函数?(爪哇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文