【问题标题】:Constructor of the super class [closed]超类的构造函数[关闭]
【发布时间】:2013-07-07 21:20:44
【问题描述】:

您好,我正在尝试从扩展其超类及其构造函数 super 的类中实例化一个对象,但在 Java 接受实例化对象的构造函数中的参数时遇到了困难,有人可以帮帮我吗,谢谢你!这是程序:

public class Box {

    double width;
    double height;
    double depth;

    Box(Box ob)
        {
            this.width=ob.width;
            this.height=ob.height;
            this.depth=ob.depth;           
        }
    Box(double width, double height, double depth)
        {
            this.width=width;
            this.height=height;
            this.depth=depth;
        }

    double volume()
        {
            return width * height * depth;
        }


}


public class BoxWeight extends Box{

    double weight;
    BoxWeight(BoxWeight object)
        {
            super(object);
            this.weight=object.weight;
        }
    BoxWeight(double w, double h, double d, double wei)
        {

            super(w,h,d);
            this.weight=wei;
        }

}


public class Proba {


    public static void main(String[] args) {

        BoxWeight myBox1 = new BoxWeight();
        BoxWeight myBox2 = new BoxWeight();

    }
}

现在,每当我尝试将参数传递给主类中的 BoxWeight() 构造函数时,就会出现错误。

【问题讨论】:

  • 您没有将任何参数传递给 main() 中的构造函数???!请澄清。另请阅读 - stackoverflow.com/questions/how-to-ask
  • 好的,每当我尝试将参数传递给构造函数或将它们留空时,Net Beans 都会抛出错误,在最后 2 行代码的行中显示 2 个红色圆圈Proba 类: BoxWeight myBox1 = new BoxWeight(); BoxWeight myBox2 = new BoxWeight();没有为 BoxWeight() 找到合适的构造函数 构造函数 BoxWeight.BoxWeight(double,double,double,double) 不适用(实际参数列表和形式参数列表长度不同)长度不同)
  • 好吧,你刚刚回答了你自己的问题!你没有默认构造函数。
  • 什么意思我没有默认构造函数?我在 BoxWeight 类中有 2 个构造函数?如果我错了,请在空白处填写。

标签: java inheritance constructor super


【解决方案1】:

您正在为 BoxWeight 定义两个构造函数

BoxWeight(BoxWeight object)
BoxWeight(double w, double h, double d, double wei)

但尽量使用不带参数的

BoxWeight myBox1 = new BoxWeight();

因此,您需要在像这样构造对象时提供另一个实例:

BoxWeight myBox1 = new BoxWeight(someOtherBox);

或使用具有单独定义值的构造函数:

BoxWeight myBox1 = new BoxWeight(myWidth, myHeight, myDepth, myWeight);

或为您的 BoxWeight 定义一个无参数构造函数,该构造函数调用现有的 Box 构造函数之一或另一个新创建的不带参数的构造函数。

BoxWeight() {
    super(...)
}

如果您习惯于在没有实际定义的情况下调用无参数构造函数,这是因为 Java 提供了一个默认构造函数,但前提是您自己不定义任何构造函数。详情请见this page

【讨论】:

  • 哦,我听到了,非常感谢先生。
  • 如果您的问题得到解决,请将对您帮助最大的答案标记为已接受。
  • 是的,我知道,如果我不自己在问题的某个地方构建构造函数,Java 会默认为我创建一个无参数的构造函数,但我不知道我应该这样做在创建其他几个参数构造函数时放置一个无参数的构造函数。谢谢!
猜你喜欢
  • 2018-08-10
  • 2023-03-03
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 2021-11-11
  • 2018-07-11
  • 2014-11-20
相关资源
最近更新 更多