【问题标题】:Java Inheritance error: Implicit Super Constructor is undefinedJava 继承错误:隐式超级构造函数未定义
【发布时间】:2012-02-04 18:31:29
【问题描述】:

我是 Java 新手,刚刚学习 OOP 概念。请查看我的代码。我收到以下错误。- 隐式超级构造函数未定义。

class BoxSuper
{
    int height;
    int length;
    int width;

    BoxSuper(BoxSuper obj)
    {
        height=obj.height;
        length=obj.length;
        width=obj.width;
    }
    BoxSuper(int a,int b,int c)
    {
        height=a;
        length=b;
        width=c;
    }
    BoxSuper(int val)
    {
        height=length=width=val;
    }
    int volume()
    {
        return height*length*width;
    }
}

class BoxSub extends BoxSuper
{
    int weight;
    BoxSub(int a,int b,int c,int d)
    {
        height=a;
        length=b;
        width=c;
        weight=d;
    }
}

【问题讨论】:

标签: java inheritance constructor


【解决方案1】:

您收到此错误是因为 BoxSuper 没有无参数构造函数。在 BoxSub 中调用构造函数期间,如果未定义超级构造函数调用,Java 会尝试自动调用无参数 super() 构造函数。

在 BoxSuper 中定义一个超级构造函数调用,如下所示:

class BoxSub extends BoxSuper
{
    int weight;
    BoxSub(int a,int b,int c,int d)
    {
        super(a, b, c);
        weight=d;
    }
}

或者在 BoxSuper 中定义一个无参数的构造函数:

class BoxSuper
{
    int height;
    int length;
    int width;

    BoxSuper(){}
...

【讨论】:

  • 如果我是你,我会改用 super(a,b,c) 调用并利用你已经定义的 BoxSuper 中的构造函数。好吧,祝你学习顺利。
【解决方案2】:

构造函数总是调用超级构造函数,总是。如果没有显式调用超级构造函数,则编译器会尝试对其进行设置,以便调用默认的无参数构造函数。如果默认的无参数构造函数不存在,则会显示您所看到的编译错误并且编译将失败。

在您的情况下,解决方案是显式调用适当的超级构造函数作为 Box 构造函数的第一行,如果您考虑一下,这也很有意义,因为您想初始化超级使用 a、b 和 c,就像在其构造函数中所写的那样:

class BoxSub extends BoxSuper
{
    int weight;
    BoxSub(int a,int b,int c,int d)
    {
        super(a, b, c);
        // height=a;
        // length=b;
        // width=c;
        weight=d;
    }
}

【讨论】:

  • 试过这个..它不工作......但我担心的是子类在我的代码中继承了超类的所有变量和方法。为什么它仍然抛出未定义的构造函数?
  • @Venk:嗯,“它不工作”并不能告诉我们太多。您仍然有错误,需要向我们展示您更新的代码尝试以及您看到的任何错误消息。
  • @Venk,你是什么意思它不起作用?你看到了什么错误?
  • 默认构造函数不可见的相同错误
猜你喜欢
  • 2010-11-14
  • 2020-06-05
  • 1970-01-01
  • 2013-09-20
  • 2013-09-28
  • 2014-10-02
  • 2014-06-26
  • 2018-06-27
  • 2021-11-15
相关资源
最近更新 更多