我有一個類層次結構,低於顯示:類對象比較 - 獲取錯誤輸出equals方法
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 boolean equals(Object b)
{
if (! (b instanceof Rectangle2))
return false;
Box2 t = (Box2)b;
Cube c = (Cube)b;
return t.getLength() == getLength()
&& t.getWidth() == getWidth()
&& c.getLength() == getLength()
&& c.getWidth() == getWidth() ;
}
}
。
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 boolean equals(Object b)
{
if (! (b instanceof Box2))
return false;
Rectangle2 t = (Rectangle2)b;
Cube c = (Cube)b;
return t.getLength() == getLength()
&& t.getWidth() == getWidth()
&& c.getLength() == getLength() ;
}
}
。
public class Cube extends Box2 {
public Cube(int length)
{
super(length, length, length);
}
public String toString()
{
return "Cube - " + getLength() + " X " + getWidth() + " X " + getHeight();
}
public boolean equals(Object b)
{
if (! (b instanceof Cube))
return false;
Rectangle2 t = (Rectangle2)b;
Box2 c = (Box2)b;
return t.getLength() == getLength()
&& t.getWidth() == getWidth()
&& c.getLength() == getLength()
&& c.getWidth() == getWidth()
&& c.getHeight() == getHeight() ;
}
}
我創建了equals()
方法,這樣,當一個類的實例會等於其他它會打印一些類似「這一類的尺寸等於該類的尺寸。」這將是一個例子:http://i.stack.imgur.com/Kyyau.png 唯一的問題是我沒有得到那個輸出。當我正在爲Cube類執行equals()
方法時,我還可以繼承Box2類的equals()
方法嗎?
我不明白。當你在所有的代碼中沒有一個'print' /'println'時,你希望你的程序能夠打印'...與......相同的大小? – us2012 2013-03-20 18:57:40
你爲什麼要投射一個Rectangle2到它的sublcass實例?誰這樣做,爲什麼? – ITroubs 2013-03-20 18:58:39
@ us2012我試圖把一個println放在equals類中,但它不會讓我。 – user2059140 2013-03-20 19:00:04