在 java 中与 super 合作

Working with super in java

对于 Cube class,我正在尝试消除错误:

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 的每个面都是一个 Rectangle,其长度和宽度需要与 Cube 的边相同,但我不确定需要将什么传递给 Rectangle 构造函数以使其长度和宽度与立方体的边相同。

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

这是立方体class

// ---------------------------------
// 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();}
}

这是矩形 class

// ---------------------------------
// 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) 中的参数数量与 class Rectangle 的构造函数中的参数不匹配。当您显式调用 super class 构造函数时,您必须确保 super class 具有匹配的构造函数。

Rectangle 的超类是 Cube 而不是 Point。使用 super() 你可以调用 Cube 的构造函数而不是 Point

的构造函数

这个对象的构造本身似乎没有考虑到扩展的概念。

Cube 不是 Rectangle。一个 Cube 可以被认为是多个 Rectangle 的组合,具有用于方向的空间数据,但是矩形应该是 Cube.[= 的成员(读取 attributes/fields) 30=]

为了说明这一点,请考虑以下陈述之间的区别。

所有立方体都是矩形。

所有的猫都是动物。

你可以想像地创建一个 Cat 对象来扩展超级 class AnimalCubes 和 Rectangles 不共享此关系。

考虑将您的代码重构为:

public class Cube {
    private List<Rectangle> faces:

    ....

}

更进一步,并非所有 Rectangle 都是 Point

一个点是一对x、y坐标。为了准确绘制 Rectangle 所需的最少信息量是两个 Point

+--
| |
--+

如果你有对角 Points(这里用 + 标记)你可以画你的 Rectangle.

鉴于此,也许您还应该重构 Rectangle 以拥有一对 Point 作为成员。

类似于:

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

    ...
}