有没有一种方法可以调用从没有自己的构造函数的子 class 获取参数的父 class 构造函数?
Is there a way I can call a parent class constructor that takes parameters from a child class that does not have a constructor of it's own?
众所周知,parentclass必须在childclass之前构造;如果父级的 class 构造函数接受参数,则必须显式调用父级 class 的构造函数。我的问题是,如果子 class 本身没有构造函数,您如何调用从子 class 显式获取参数的父 class 构造函数?
public class A {
public String text;
public A(String text) {
this.text = text;
}
}
public class B extends A {
// Now I must call the constructor of A explicitly (other wise I'll get a
// compilation error) but how can I do that without a constructor here?
}
您收到编译错误,因为 class A
中没有默认构造函数。您可以在 B
中创建一个无参数构造函数并将一些默认文本传递给 A
的构造函数,或者在 A
.
中创建一个无参数构造函数
public B() {
super("some default text"); //will call public A(String text)
}
答案是:不能!
如果 super class 有一个无参数构造函数,编译器也可以在 subclass 中为您添加一个类似的构造函数。
但是当超级class需要参数时,编译器不知道这些应该从哪里来。
因此:考虑向 super class 添加一个无参数构造函数,它可以调用另一个构造函数并传递某种默认值。或者,您可以在派生的 class.
中执行相同的操作
郑重声明:没有 Java classes 没有构造函数。只是编译器可能会在幕后为您创建一个。从这个角度来看,你的问题没有多大意义。
如果您不愿意直接调用父构造函数,您只需要在只调用父构造函数的子class中添加一个具有相同参数的构造函数。
public class A {
public String text;
public A(String text)
{
this.text = text;
}
}
public class B extends A
{
public B(String text)
{
super(text);
}
}
众所周知,parentclass必须在childclass之前构造;如果父级的 class 构造函数接受参数,则必须显式调用父级 class 的构造函数。我的问题是,如果子 class 本身没有构造函数,您如何调用从子 class 显式获取参数的父 class 构造函数?
public class A {
public String text;
public A(String text) {
this.text = text;
}
}
public class B extends A {
// Now I must call the constructor of A explicitly (other wise I'll get a
// compilation error) but how can I do that without a constructor here?
}
您收到编译错误,因为 class A
中没有默认构造函数。您可以在 B
中创建一个无参数构造函数并将一些默认文本传递给 A
的构造函数,或者在 A
.
public B() {
super("some default text"); //will call public A(String text)
}
答案是:不能!
如果 super class 有一个无参数构造函数,编译器也可以在 subclass 中为您添加一个类似的构造函数。
但是当超级class需要参数时,编译器不知道这些应该从哪里来。
因此:考虑向 super class 添加一个无参数构造函数,它可以调用另一个构造函数并传递某种默认值。或者,您可以在派生的 class.
中执行相同的操作郑重声明:没有 Java classes 没有构造函数。只是编译器可能会在幕后为您创建一个。从这个角度来看,你的问题没有多大意义。
如果您不愿意直接调用父构造函数,您只需要在只调用父构造函数的子class中添加一个具有相同参数的构造函数。
public class A {
public String text;
public A(String text)
{
this.text = text;
}
}
public class B extends A
{
public B(String text)
{
super(text);
}
}