扩展类时构造函数出错 [英] Error on constructor while extending class

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

问题描述

我是Java的初学者,在编码过程中,我遇到了一个我不容易理解的问题.我的问题是用一种方法来找到一个矩形的区域来编写一个类.创建一个子类来查找一个矩形框的体积."我面临的错误如下.我是用相同的代码编写的:-

I am a beginner in java and during coding, i faced an issue which is not easy to understand for me. My question is "Write a class with a method to find the area of a rectangle. Create a subclass to find the volume of a rectangular shaped box." The error i am facing is below. I wrote this code for the same:-

class Rectangle
{
    public int w;
    public int h;

    public Rectangle(int width, int height)
    {
        w=width;
        h=height;
    }
    public void area()
    {
        int area=w*h;
        System.out.println("Area of Rectangle : "+area);
    }
}
class RectangleBox extends Rectangle
{
    int d;
    public RectangleBox(int width, int height, int depth)
    {
        d=depth;
        w=width;
        h=height;   

    }
    public void volume()
    {
        int volume=w*h*d;
        System.out.println("Volume of Rectangle : "+volume);
    }
}
class programm8
{
    public static void main(String args[])
    {
    Rectangle r = new Rectangle(10,20);
    RectangleBox rb = new RectangleBox(4,5,6);
    r.area();
    rb.volume();
    }
}

错误:(23,5)java:类代码中的构造函数Rectangle.Rectangle不能应用于给定类型;必需:int,int找到:否论点原因:实际和正式论点列表的长度不同

Error:(23, 5) java: constructor Rectangle in class code.Rectangle cannot be applied to given types; required: int,int found: no arguments reason: actual and formal argument lists differ in length

推荐答案

首先创建子对象时,父构造函数起作用.在此示例中,当您创建RectangleBox对象时,首先在该RectangleBox构造函数起作用之后,Rectangle构造函数起作用.因此,您的子构造函数必须调用父构造函数.

When you create a child object firstly a parent constructor works. In this example when you create a RectangleBox object, firstly Rectangle constructor works after that RectangleBox constructor works. So, your child constructor have to call a parent constructor.

通常,如果您具有父类和子类的默认构造函数,则子默认构造函数将调用父默认构造函数.但是您没有默认的构造函数,因为此RectangleBox构造函数必须调用Rectangle构造函数.为了调用父构造函数,您必须使用 super 关键字.然后是您的代码:

Normally if you have default constructors for parent and child classes, child default constructor calls parent default constructor. But you dont have default constructors because of this RectangleBox constructor have to call a Rectangle constructor. And for calling a parent contructor you have to use super keyword. And then your code:

public Rectangle(int width, int height)
    {
        w=width;
        h=height;
    }

public RectangleBox(int width, int height, int depth)
    {
        super(width, width)
        h=height;   

    }

这篇关于扩展类时构造函数出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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