默认构造函数未定义隐式超级构造函数

默认构造函数未定义隐式超级构造函数

本文介绍了Java错误:默认构造函数未定义隐式超级构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些简单的Java代码,在其结构中看起来与此类似:

I have a some simple Java code that looks similar to this in its structure:

abstract public class BaseClass {
    String someString;
    public BaseClass(String someString) {
        this.someString = someString;
    }
    abstract public String getName();
}

public class ACSubClass extends BaseClass {
    public ASubClass(String someString) {
        super(someString);
    }
    public String getName() {
        return "name value for ASubClass";
    }
}

我将有很多<$ c的子类$ c> BaseClass ,每个都以自己的方式实现 getName()方法()。

I will have quite a few subclasses of BaseClass, each implementing the getName() method in its own way (template method pattern).

这很好用,但我不喜欢冗余构造函数在子类中。打字更多,难以维护。如果我要更改 BaseClass 构造函数的方法签名,我将不得不更改所有子类。

This works well, but I don't like having the redundant constructor in the subclasses. It's more to type and it is difficult to maintain. If I were to change the method signature of the BaseClass constructor, I would have to change all the subclasses.

当我从子类中删除构造函数时,我得到了这个编译时错误:

When I remove the constructor from the subclasses, I get this compile-time error:

隐式超类构造函数BaseClass()未定义为默认构造函数。必须定义一个显式构造函数

我正在尝试做什么?

推荐答案

您收到此错误,因为没有构造函数的类具有默认构造函数,该构造函数是无参数且等效于以下代码:

You get this error because a class which has no constructor has a default constructor, which is argument-less and is equivalent to the following code:

public ACSubClass() {
    super();
}

但是,因为你的BaseClass声明了一个构造函数(因此没有默认值) ,编译器将提供的no-arg构造函数)这是非法的 - 扩展BaseClass的类不能调用 super(); 因为没有无参数BaseClass中的构造函数。

However since your BaseClass declares a constructor (and therefore doesn't have the default, no-arg constructor that the compiler would otherwise provide) this is illegal - a class that extends BaseClass can't call super(); because there is not a no-argument constructor in BaseClass.

这可能有点违反直觉,因为您可能认为子类自动拥有基类所具有的任何构造函数。

This is probably a little counter-intuitive because you might think that a subclass automatically has any constructor that the base class has.

最简单的方法是让基类不要声明构造函数(因此有默认的no-arg构造函数)或者有一个声明的无参数构造函数(无论是单独还是旁边)任何其他构造函数)。但是通常不能应用这种方法 - 因为你需要传递给构造函数的任何参数来构造类的合法实例。

The simplest way around this is for the base class to not declare a constructor (and thus have the default, no-arg constructor) or have a declared no-arg constructor (either by itself or alongside any other constructors). But often this approach can't be applied - because you need whatever arguments are being passed into the constructor to construct a legit instance of the class.

这篇关于Java错误:默认构造函数未定义隐式超级构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:47