在java中使用super

在java中使用super,java,constructor,return,super,Java,Constructor,Return,Super,对于Cube类,我试图消除错误: Cube.java:12: error: constructor Rectangle in class Rectangle cannot be applied to given types; super(x, y); ^ required: int,int,double,double found: int,int....... 我知道立方体的每个面都是一个矩形,其长度和宽度必须与立方体的侧面相同,但我不确定需要传递给矩形构造函数什么才能

对于
Cube
类,我试图消除错误:

Cube.java:12: error: constructor Rectangle in class Rectangle cannot be applied to given types;
    super(x, y);
    ^
  required: int,int,double,double
  found: int,int.......
我知道立方体的每个面都是一个矩形,其长度和宽度必须与立方体的侧面相同,但我不确定需要传递给矩形构造函数什么才能使其长度和宽度与立方体的侧面相同

还尝试计算体积,即矩形的面积乘以立方体边的长度

这是多维数据集类

// ---------------------------------
// File Description:
//   Defines a Cube
// ---------------------------------

public class Cube extends Rectangle
{


  public Cube(int x, int y, int side)
  {
    super(x, y);
    side = super.area(); // not sure if this is right
  }


  public int    getSide()   {return side;}

  public double area()      {return 6 * super.area();}
  public double volume()    {return super.area() * side;}
  public String toString()  {return super.toString();}
}
这是矩形类

// ---------------------------------
// File Description:
//   Defines a Rectangle
// ---------------------------------

public class Rectangle extends Point
{
  private int    x, y;  // Coordinates of the Point
  private double length, width;

  public Rectangle(int x, int y, double l, double w)
  {
    super(x, y);
    length = l;
    width = w;
  }

  public int       getX()         {return x;}
  public int       getY()         {return y;}
  public double    getLength()    {return length;}
  public double    getWidth()     {return width;}

  public double area()      {return length * width;}
  public String toString()  {return "[" + x + ", " + y + "]" + " Length = " + length + " Width = " + width;}
}

问题是
Rectangle
构造函数需要4个参数,而在创建
Cube
的实例时,您只传递了2个参数。你也应该通过你的长度:

  public Cube(int x, int y, int side)
  {
    super(x, y, side, side);
  }

如果你觉得有点道理的话——任何矩形都需要原点x和y,以及宽度和高度。如果立方体的宽度和高度相同,但仍应告诉矩形它们的值;)

您的
super(x,y)
中的参数数量与类
矩形的构造函数中的参数不匹配。当您显式调用超类构造函数时,您必须确保超类有一个匹配的构造函数。

矩形的超类是
立方体
而不是
。使用
super()

立方体
不是
矩形
。一个
多维数据集
可以被视为是多个
矩形
与空间数据的组合,但矩形应该是
多维数据集
的成员(读取属性/字段)

为了说明这一点,请考虑下列语句之间的差异。

所有立方体都是矩形

所有的猫都是动物

可以想象,您可以创建一个
Cat
对象来扩展超类
Animal
Cube
s和
Rectangle
s不共享此关系

考虑将您的代码重构为:

public class Cube {
    private List<Rectangle> faces:

    ....

}
public class Rectangle {
    private Point firstCorner;
    private Point secondCorner;

    ...
}
如果您有相对的角
s(这里用+标记),您可以绘制您的
矩形

有鉴于此,也许您还应该重构
矩形
,将一对
作为成员

比如:

public class Cube {
    private List<Rectangle> faces:

    ....

}
public class Rectangle {
    private Point firstCorner;
    private Point secondCorner;

    ...
}

由于
Rectangle
没有接受两个参数的构造函数,因此在调用
super(x,y)时,您希望调用什么代码
?您确定您的
多维数据集
需要继承自
矩形
,而不是简单地保存一组
矩形
,每个矩形都有自己的
点和长度吗?另外,由于
矩形
扩展了
,因此不需要在
矩形
中定义
x
y
getX
getY
,而是继承这些属性。