【发布时间】:2023-03-10 05:48:01
【问题描述】:
在java中定义Derived类的构造函数有两种方式。
在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() implicilty。
在下面稍作改动的代码中,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);
}
}
【问题讨论】:
-
super()没有“定义构造函数”。它调用 parent 构造函数。不清楚你在问什么。 -
1)
this.id = 0;是多余的,因为数字字段默认为 0。 --- 2) 是的,super()在构造函数开始时被隐式调用,如果没有显式调用。 --- 3)id、this.id和super.idall 指的是BaseClass的唯一id字段。 --- 4) 为什么id在你赋予它那个值之后不会是10?
标签: java inheritance constructor