我的家庭作业有一个奇怪的问题。下面是一个类声明。
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
但我需要这个构造函数有所不同。我怎样才能做到这一点?
最佳答案
首先你的基类有自定义构造函数但没有默认构造函数,这会导致编译错误。派生类将在派生类构造函数的第一行调用基类的隐式默认构造函数,或者您可以根据您的需要调用必要的基类构造函数(super(..)),然后调用接下来的构造函数体。 所以使用不同的构造函数不是问题。
关于java - 在子类中定义与父类(super class)构造函数不同的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35129436/