Java 在不同于超类构造函数的子类中定义构造函数?
我的家庭作业中有个奇怪的问题。下面是一个类声明Java 在不同于超类构造函数的子类中定义构造函数?,java,inheritance,constructor,Java,Inheritance,Constructor,我的家庭作业中有个奇怪的问题。下面是一个类声明 public class A { private String str; private int num; public A ( String str, int num ) { this.str = str; this.num = num; } 现在我需要一个子类的实现,该子类继承自a类,但有一个不同的构造函数,如下所示: public class B extends A { private String str1;
public class A {
private String str;
private int num;
public A ( String str, int num ) {
this.str = str;
this.num = num;
}
现在我需要一个子类的实现,该子类继承自a类,但有一个不同的构造函数,如下所示:
public class B extends A {
private String str1;
public B ( String str, String str1 ) {...}
// this is where the editor shows an error because class B constructor arguments are
// different from the arguments in the class A constructor
但我需要这个构造函数是不同的。如何执行此操作?您需要显式调用超级构造函数:
public class B extends A {
private String str1;
public B ( String str, String str1 ) {
super(str,0);
//do what you want...
}
您需要显式调用超级构造函数:
public class B extends A {
private String str1;
public B ( String str, String str1 ) {
super(str,0);
//do what you want...
}
您必须使用
super()
语句:
public B ( String str, String str1 ) {
//0 is the second int argument of the class A constructor
super(str, 0);
//do something with the str1
}
因为您的类A
不再具有默认无参数
构造函数,如果没有,则由编译器创建
在类中定义的构造函数
您必须使用
super()
语句:
public B ( String str, String str1 ) {
//0 is the second int argument of the class A constructor
super(str, 0);
//do something with the str1
}
因为您的类A
不再具有默认无参数
构造函数,如果没有,则由编译器创建
在类中定义的构造函数
首先,基类有自定义构造函数,但没有默认构造函数,这将导致编译错误。派生类将在派生类构造函数的第一行调用基类的隐式默认构造函数,或者您可以根据需要调用必要的基类构造函数(super(..),然后调用接下来的构造函数体。
因此,使用不同的构造函数不是问题。首先,基类有自定义构造函数,但没有默认构造函数,这将导致编译错误。派生类将在派生类构造函数的第一行调用基类的隐式默认构造函数,或者您可以根据需要调用必要的基类构造函数(super(..),然后调用接下来的构造函数体。
所以有不同的构造函数不是问题。谢谢,我不知道我们可以给super();像这样的参数(即0),最后一件事,“0”在超级参数中代表什么?构造函数不能被重写。@FabioÇimo 0是一个int,是超级构造函数所需的第二个参数。谢谢你,我不知道我们可以给出super();像这样的参数(即0),最后一件事,“0”在超级参数中代表什么?构造函数不能被重写。@FabioÇimo 0是一个int,是超级构造函数所需的第二个参数。对,它可以工作,但是“0”在超级()中代表什么;?0是类A构造函数的第二个int参数:num变量。。您必须根据示例logicRight来决定将什么int作为参数传递,它是有效的,但是“0”在super()中代表什么;?0是类A构造函数的第二个int参数:num变量。。您必须根据示例逻辑来决定将什么int作为参数传递