需要无参数的子类构造函数,但超类没有它

时间:2013-07-03 21:09:34

标签: java inheritance

这里的OOP初学者...我有一个名为Rectangle的超类,它有一个构造函数,它接受int height和int width作为参数。我的任务是创建一个改进的Rectangle子类,其中包括一个不需要参数的构造函数。

那么,如何在不搞乱超类的情况下做到这一点?

public class BetterRectangle extends Rectangle
{
    public BetterRectangle(int height, int width)
    {
        super(height,width);
    }

    public BetterRectangle()
    {
            width = 50;
            height = 50; 
    }
}

这给了我“隐式超级构造函数未定义”。显然我需要调用超类构造函数。但是用什么?只是随机值,稍后会被覆盖?

1 个答案:

答案 0 :(得分:6)

试试这个:

public BetterRectangle()
{
        super(50, 50); // Call the superclass constructor with 2 arguments 
}

或者:

public BetterRectangle()
{
        this(50, 50); // call the constructor with 2 arguments of BetterRectangle class.
}

你不能使用你的代码,因为构造函数中的第一行是对super()或this()的调用。如果没有调用super()或this(),则调用是隐式的。您的代码相当于:

public BetterRectangle()
{
        super(); // Compile error: Call superclass constructor without arguments, and there is no such constructor in your superclass.
        width = 50;
        height = 50; 
}