我有疑问是否可以在抽象类的另一个构造函数中调用构造函数。例如,
public abstract class Sth{
protected Sth(){}
protected Sth(int number){}
protected Sth(String word){
int number = 0;
this(number);
}
Java似乎不允许我这样做。我想知道是否有什么办法可以让这种情况发生?谢谢
------------------------------------------------------------说明- -------------------------------------------------- ------------------- 我想要做的目标是专门调用第二个构造函数。我遇到错误,必须调用 Java 中的第一个构造函数。所以我想知道我们是否可以跳过第一个构造函数而不删除这里的任何代码。对困惑感到抱歉。
您想要以下代码吗?
public abstract class Sth {
protected Sth() {}
protected Sth(int number) {}
protected Sth(String word, int number) {
this(number);
}
}
其实答案是,抽象类构造函数是不能用的。因此,我们无法实例化它。检查Java文档
也许这会有所帮助
abstract class SthAbstract {
SthAbstract() {
System.out.println("Default Constructor Calling...");
}
SthAbstract(String word, int number) {
System.out.println("2 Parameter Constructor Calling..."+word+"..."+number);
}
protected SthAbstract(int number) {
System.out.println("1 Parameter Constructor Calling..."+number);
}
}
public class Sth extends SthAbstract {
// if we dont make any Constructor then default Constructor call of abstract class
Sth() {
super();
}
Sth(int number) {
super(number);
}
Sth(String word, int number) {
super(word, number);
}
public static void main(String[] args) {
Sth obj = new Sth(10);
Sth obj1 = new Sth("Peeter Parker", 13);
}
}