【问题标题】:Java: Extending a class, constructor of subclass gives errorJava:扩展一个类,子类的构造函数给出错误
【发布时间】:2013-10-16 15:09:06
【问题描述】:

一点背景:

涉及三个类:Tester(main method)DNASequence(object)ProteinDNA(subclass of DNASequence)。这三个都在同一个包下。

ProteinDNA 的构造函数接受一个对象 DNASequence 和一个整数

public class ProteinDNA extends DNASequence{
public ProteinDNA(DNASequence dna, int startAt){   //this is the constructor

编译类 ProteinDNA 在构造函数中给我一个错误。

Eclipse中的错误是:

"Implicit super constructor `DNASequence()` is undefined.
 Must explicitly invoke another constructor"

jGrasp中的错误是:

ProteinDNA.java:16: error: 
   constructor DNASequence in class DNASequence cannot be applied to given types;
public ProteinDNA(DNASequence dna, int startAt)^{


     required: String

     found: no arguments

     reason: actual and formal argument lists differ in length"

我做错了什么? Tester 类为ProteinDNA 提供一个适当构造的DNASequence 实例。

【问题讨论】:

  • ProteinDNA 是一个 DNASequence,因此您需要显式调用DNASequence构造函数,因为它似乎没有无参数构造函数。跨度>
  • 在 DNASequence 中创建无参数构造函数可以解决问题!谢谢!
  • @user1766889:好吧,它会修复编译时错误——但它可能实际上并没有达到你想要的效果。你确定ProteinDNA 应该扩展DNASequence 吗?它在其构造函数中接受一个似乎很奇怪扩展它......
  • 这并不太奇怪,因为第二个参数是一个 int,它是 DNASequence 上的索引。所以ProteinSequence 只是DNASequence 类的一部分。这不像是我将超类的整个实例复制到子类的实例中。

标签: java subclass superclass


【解决方案1】:
Parent Class DNASequence has existing constructor with parameters. There 2 solutions for this.

1) 您可以在 DNA 序列类中添加默认的无参数构造函数。

2) 修改子类构造函数以调用父类构造函数,如下所示,

    public ProteinDNA(DNASequence dna, int startAt){

   super(....); // This should be the 1st line in constructor code, add parameters 
                as per parent constructor 
}

【讨论】:

    【解决方案2】:

    看起来您正在尝试传递一个 DNASequence 对象,而失败的是该对象的构建。

    必需:字符串
    发现:没有参数

    这让我觉得您可能会尝试执行以下操作:

    new ProteinDNA(new DNASequence(), num);
    

    编译器说它需要一个字符串:

    new ProteinDNA(new DNASequence("SOME STRING"), num);

    这有意义吗?

    如果您发布一些特定的代码,也许我们会更有帮助,即:

    • ProteinDNA 构造函数调用
    • DNASequence 构造函数签名
    • 测试方法的代码

    另外,您能否解释一下,如果 ProteinDNA 是 DNASequence 的子类,您将 DNASequence 传递给它的构造函数?这是某种防御性副本吗?

    另外,如替代答案中所述,您可能希望将对超级构造函数 (DNASequence(String)) 的调用添加到子构造函数,作为第一行,如下所示:

    super("SOME STRING")
    

    但这真的取决于你的逻辑......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多