继承java在派生构造函数中调用超级构造函数,与设置字段值完全相同?
在java中定义派生类的构造函数有两种方法
在DerivedClassWithSuper
中,我使用super()
函数来定义构造函数。
但是,在DerivedClassWithoutSuper
中,我不使用super()
函数来定义构造函数
我想知道的一件事是,它们之间有什么区别吗
我也知道DerivedClassWithSuper
的代码看起来更好,但我不确定在DerivedClassWithoutSuper
中定义构造函数时是否有任何副作用
class BaseClass {
int id;
BaseClass () {
this.id = 0;
System.out.printf("Base class is created, id: %d \n", this.id);
}
}
class DerivedClassWithSuper extends BaseClass {
String name;
DerivedClassWithSuper () {
super();
// this.id = 0;
this.name = "Unknown";
System.out.printf("DerivedClassWithSuper is created, this.id: %d, name: %s\n", this.id, this.name);
}
}
class DerivedClassWithoutSuper extends BaseClass {
String name;
DerivedClassWithoutSuper () {
this.id = 0;
this.name = "Unknown";
System.out.printf("DerivedClassWithoutSuper is created, id: %d, name: %s\n", this.id, this.name);
}
}
我一直感谢你的帮助。谢谢
其他问题:
如果没有super()
函数,则派生类隐式调用super()
在下面稍加修改的代码中,在DerivedClassWithoutSuper
构造函数中将this.id
设置为10,并隐式调用super()
函数。如果调用super()
,则this.id
或super.id
应设置为0
但是,super.id
和this.id
是10
我不明白为什么会这样
class BaseClass {
int id;
BaseClass () {
this.id = 0;
System.out.printf("Base class is created, id: %d \n", this.id);
}
}
class DerivedClassWithSuper extends BaseClass {
String name;
DerivedClassWithSuper () {
super();
this.name = "Unknown";
System.out.printf("DerivedClassWithSuper is created");
System.out.printf("%d %d\n", this.id, super.id);
}
}
class DerivedClassWithoutSuper extends BaseClass {
String name;
DerivedClassWithoutSuper () {
// if super() implicitly called?
this.id = 10;
this.name = "Unknown";
System.out.printf("DerivedClassWithoutSuper is created\n");
// then this.id and super.id should be different.
// but, both are 10 as set in this constructor.
System.out.printf("%d %d\n", this.id, super.id);
}
}
# 1 楼答案
如果子类构造函数没有显式地调用
super(...)
(或this(...)
),编译器将隐式地为您调用no-argsuper()
构造函数。如果不存在这样的构造函数,编译将失败,即使您从未编写过调用参见例如The Java™ Tutorials - Using the Keyword super: