以下に示すクラス階層があります...
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() メソッドをすべてのクラスに追加して、あるクラスの出力が他のクラスの出力と等しい場合に「ボックスとキューブは同じ次元を持っています」と出力するようにします。私は本当に混乱しています。私が知っているのは、if-else
ステートメントを使用する必要があるということだけですが、その後はどうすればよいかわかりません。
これが私の質問の内容です: 3. クラスに equals() メソッドを追加して、2 つの Rectangle、Box、または Cube がそれらの寸法の値に基づいていつ等しいかを判断できるようにします。Cube は、Box クラスの equals メソッドをオーバーライドするのではなく、継承する必要があります。出力は次のようになります: http://i.stack.imgur.com/Kgti1.png