java - 在子类中定义与父类(super class)构造函数不同的构造函数?

标签 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 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/

相关文章:

java - GWT:在超链接上添加 clickHandler

java - 计算递归算法的时间复杂度。

Java:同步标准输出和标准错误

C#构造函数执行顺序

c++ - struct 中不可访问的模板化构造函数

java - 在 lucene 中搜索 UUID 不起作用

c++ - 在继承方面需要帮助

c# - 实体设计与继承

java - 无法创建构造函数

Java、泛型和继承