我有一个类层次结构,如下所示:
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
唯一的问题是我没有得到那个输出。equals()
当我equals()
为 Cube 类做方法时,我也可以只从 Box2 类继承方法吗?