这里是 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/