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

Ben*_*ist 0 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; 
    }
}
Run Code Online (Sandbox Code Playgroud)

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

ete*_*nay 6

试试这个:

public BetterRectangle()
{
        super(50, 50); // Call the superclass constructor with 2 arguments 
}
Run Code Online (Sandbox Code Playgroud)

要么:

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

您不能使用您的代码,因为构造函数中的第一行是对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; 
}
Run Code Online (Sandbox Code Playgroud)