在java中使用super

Hoo*_*ege 7 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.......
Run Code Online (Sandbox Code Playgroud)

我知道立方体的每个面都是一个矩形,其长度和宽度需要与立方体的边相同但我不确定需要传递给Rectangle构造函数以使其长度和宽度与一个立方体的一面.

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

这是Cube类

// ---------------------------------
// 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();}
}
Run Code Online (Sandbox Code Playgroud)

这是矩形类

// ---------------------------------
// 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;}
}
Run Code Online (Sandbox Code Playgroud)

Bla*_*ugh 10

这个对象的构造似乎错过了扩展的想法.

A Cube不是Rectangle.A Cube可以被认为是Rectangle具有空间数据的多个s 的复合,但是矩形应该是成员的(读取属性/字段)Cube.

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

所有立方体都是矩形.

所有的猫都是动物.

你可以想象创建一个Cat扩展超类的对象Animal.Cubes和Rectangles不分享这种关系.

考虑重构您的代码,如下所示:

public class Cube {
    private List<Rectangle> faces:

    ....

}
Run Code Online (Sandbox Code Playgroud)

为了更进一步,不是所有Rectangle的都是Points.

一个点是一对x,y坐标.为了准确地绘制Rectangle所需的最小信息量是两个Points.

看到

+--
| |
--+
Run Code Online (Sandbox Code Playgroud)

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

鉴于此,也许你应该重构Rectangle一对Points作为成员.

就像是:

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

    ...
}
Run Code Online (Sandbox Code Playgroud)