java构造函数错误:类中的构造函数不能应用于给定的类型 [英] java constructor error: constructor in class cannot be applied to given types

查看:455
本文介绍了java构造函数错误:类中的构造函数不能应用于给定的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是java新手我不太了解继承或构造函数。

在扩展类时是否有使用构造函数的限制(如参数数量)?

这是我的程序:

I am new to java I don't know much about inheritance or constructors.
Are there any restrictions for using constructors (as in number of arguments) while extending a class?
This is my program:

class Box
{
  int length,breadth,height;
  Box(int l,int b,int h)
  {
    length=l;
    breadth=b;
    height=h;
  } 
  int volume() 
  {
    return length*breadth*height;
  }
}

class BoxWeight extends Box
{
  int weight;
  BoxWeight(int l,int b,int h,int w)
  {
    length=l;
    breadth=b;
    height=h;
    weight=w;
  } 
}   

class BoxInheritance
{
  public static void main(String args[])
  {
    Box B1=new Box(5,75,4);
    BoxWeight B2=new BoxWeight(23,32,56,54);
    System.out.println("\n the volume of box1 is "+B1.volume());
    System.out.println("\n the volume of box2 is  "+B2.volume());
  }
}  

当我运行此程序时,我收到此错误:

When I run this program, I get this error:


BoxInheritance.java:29:错误:类Box中的构造函数Box不能应用于给定的类型;
{
^
必需:int,int,int
找到:无参数
原因:实际和正式参数列表长度不同
1错误

我不知道错误发生在哪里。< br>
子类构造函数是否需要与超类构造函数相同数量的参数?

I don't know where the error occurred.
Do the subclass constructors need the same number of arguments as that of superclass constructor?

推荐答案

你的BoxWeight类应该是这样的:

Your BoxWeight class should look like this :

class BoxWeight extends Box {
    int weight;

    BoxWeight(int l, int b, int h, int w) {
        super(l, b, h);
        weight = w;
    }
}

请阅读Java中的构造函数链接。

Please read constructor chaining in Java.

这篇关于java构造函数错误:类中的构造函数不能应用于给定的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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