J'ai une hiérarchie de classes qui est ci-dessous montrent:objets de classe - Obtenir la mauvaise sortie pour Equals, méthode
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() ;
}
}
J'ai créé la méthode equals()
de sorte que lorsque les instances d'une classe serait égale l'autre, elle écrirait un peu comme « Les dimensions de cette classe égale les dimensions de cette catégorie. » Ce serait un exemple: http://i.stack.imgur.com/Kyyau.png Le seul problème est que je ne reçois pas cette sortie. Aussi pourrais-je juste hériter de la méthode equals()
de la classe Box2 quand je fais la méthode equals()
pour la classe Cube?
Je ne comprends pas. Comment voulez-vous que votre programme imprime '... est de la même taille que ...' quand vous n'avez pas un seul 'print' /' println' dans tout votre code? – us2012
pourquoi voudriez-vous lancer un Rectangle2 à une instance de sa sous-classe ??? Qui fait cela et pourquoi? – ITroubs
@ us2012 J'ai essayé de mettre un println dans la classe d'égal à égal mais il ne me laissera pas. – user2059140