Java错误:默认构造函数未定义隐式超级构造函数 [英] Java error: Implicit super constructor is undefined for default constructor

查看:49
本文介绍了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";
    }
}

我将有很多 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().必须定义一个显式构造函数

我正在尝试做的事情可行吗?

Is what I am trying to do possible?

推荐答案

你得到这个错误是因为一个没有构造函数的类有一个 default 构造函数,它是无参数的,等价于以下代码:

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 声明了一个构造函数(因此没有编译器会提供的默认无参数构造函数),这是非法的 - 扩展 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.

解决此问题的最简单方法是让基类不声明构造函数(因此具有默认的无参数构造函数)或声明的无参数构造函数(单独或与任何其他构造函数一起).但通常这种方法无法应用 - 因为您需要将任何参数传递给构造函数来构造类的合法实例.

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错误:默认构造函数未定义隐式超级构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆