在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
,而是继承这些属性。