java - 子类需要无参构造函数,但父类(super class)没有

标签 java inheritance

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

那么,我该如何做到这一点而不扰乱父类(super class)呢?

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

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

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

最佳答案

试试这个:

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; 
}

关于java - 子类需要无参构造函数,但父类(super class)没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17458168/

相关文章:

java - Mockito ArgumentCaptor 验证没有捕获任何内容

c++ - 错误C2011 : 'class type redefinition - Basic Inheritance

java - 我对子类有一些问题,如何使用 super.method()

c# - 为什么将方法移入基类后,性能会缓慢下降?

C++ 模板 - 成员函数的部分特化

java - 使用 getIntent() 时 int 和 string 之间的冲突

java - 不同对象的哈希码相同

java - ABBYY 实时识别(cordova 插件)错误

java - 通过 java.sql.PreparedStatement.setBytes 进行 BINARY 比较时的空结果集

c# - 设置基类变量的值?