我有一个类层次结构,如下所示......
public class Rectangle2
{
// instance variables
private int length;
private int width;
/**
* Constructor for objects of class rectangle
*/
public Rectangle2(int l, int w)
{
// initialise instance variables
length = l;
width = w;
}
// return the height
public int getLength()
{
return length;
}
public int getWidth()
{
return width;
}
public String toString()
{
return "Rectangle - " + length + " X " + width;
}
}
.
public class Box2 extends Rectangle2
{
// instance variables
private int height;
/**
* Constructor for objects of class box
*/
public Box2(int l, int w, int h)
{
// call superclass
super(l, w);
// initialise instance variables
height = h;
}
// return the height
public int getHeight()
{
return height;
}
public String toString()
{
return "Box - " + getLength() + " X " + getWidth() + " X " + height;
}
}
.
public class Cube extends Box2 {
public Cube(int length)
{
super(length, length, length);
}
public String toString()
{
return "Cube - " + getLength() + " X " + getWidth() + " X " + getHeight();
}
}
我想为所有类添加一个 equals() 方法,这样如果一个类的输出等于其他类的输出,它将打印“Box and Cube has the same dimension”。我真的很困惑。我所知道的是我必须使用一个if-else
声明,但在那之后我就是想不出该怎么做。
这就是我的问题所说的: 3. 还向类添加一个 equals() 方法,以便您可以根据它们的尺寸值确定两个矩形、框或立方体何时相等。Cube 应该继承 Box 类的 equals 方法而不是重写它。输出应该是这样的:http: //i.stack.imgur.com/Kgti1.png