Java继承 - 构造函数 [英] Java inheritance - constructors

查看:208
本文介绍了Java继承 - 构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习我的决赛时,我在我正在学习的书中遇到了以下的话。考虑以下代码:

While studying for my finals, I came across the following statement in the book from which I am currently studying. Considering the following code :

class A {
    public A(int x) {   }
}

class B extends A {
    public B(int x ) {   }
}

是必须在类B的构造函数(super(x))中调用类A的构造函数。这本书说,它不是强制性的,因为他们有确切的数量和类型的参数。但是当我在java编译器中尝试这个时,会抛出以下错误:

is it mandatory to call the constructor of class A in the constructor of class B(super(x)). The book states that it's not mandatory, because they have the exact number and type of parameters. But when I try this in a java compiler, the following error gets thrown :


构造函数A在类A中不能是
给定类型;需要:
int找到:无参数reason:
实际和形式参数列表
长度不同

constructor A in class A cannot be applied to given types; required: int found: no arguments reason: actual and formal argument lists differ in length


推荐答案

编译器自动在开头插入 super()

The compiler automatically inserts super() in the beginning.

但是,甚至会添加构造函数参数 super()(无参数),调用超类的默认构造函数。

However, even constructors arguments, super() (without arguments) is added which invokes the default constructor of the superclass. And you don't have one, hence the error.

您必须指定 super(x)调用 A(x))或者定义一个无参数的构造函数。

You have to specify super(x) (to invoke A(x)), or define a no-argument constructor.

一种更好的错误消息:


隐式超级构造函数A()未定义。必须显式调用另一个构造函数

Implicit super constructor A() is undefined. Must explicitly invoke another constructor

这篇关于Java继承 - 构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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