首页 文章

覆盖equals()方法以检查共享继承的对象中的维度相等性

提问于
浏览
0

我已经为那些可能需要它们的人提供了涉及这个特定问题的所有四个课程 .

主要问题是在main()方法中找到,因为main方法中的最后一行会抛出一个错误,如下所示:

类java.lang.Object中的方法equals不能应用于给定的类型; required:发现java.lang.Object:Box2,Cube2原因:实际和形式参数列表的长度不同 . 您在此处使用的运算符不能用于您使用它的值类型 . 你要么在这里使用错误的类型,要么使用错误的运算符 .

我认为这个问题可能源于我在覆盖equals()方法(位于Box类中)不正确的方法 .

这是用于打印所需输出的方法,而是返回错误 .

任何有关我如何正确重写此方法的见解都将受到高度赞赏,因为我不知所措 .

public class TestNew
{
    public static void main(String []args)
    {
          Rectangle2 one = new Rectangle2(5, 20);
          Box2 two = new Box2(4, 4, 4);
          Box2 three = new Box2(4, 10, 5);
          Cube2 four = new Cube2(4);

          showEffectBoth(one);
          showEffectBoth(two);
          showEffectBoth(three);
          showEffectBoth(four);
          System.out.println(equals(two, four));
    }

    public static void showEffectBoth(Rectangle2 r)
    {
        System.out.println(r);
    }
}

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;
    }

    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;
    }

    public int getHeight()
    {
        return height;
    }

    public String equals(Box2 o, Cube2 p)
    {
        if(o.getLength() + o.getWidth() + o.getHeight() ==  p.getLength() * 3)
        {
            return o.toString() + " is the same size as " + p.toString();
        }
        else
        {
            return o.toString() + " is not the same size as " + p.toString();
        }
    }

    public String toString()
    {
        return "Box - " + getLength() + " X " + getWidth() + " X " + height;
    }
}

public class Cube2 extends Box2
{
    /**
     * Constructor for objects of class Cube.
     */
    public Cube2(int l)
    {
        // call superclass
        super(l, l, l);
    }

    public String toString()
    {
        return "Cube - " + getLength() + " X " + getLength() + " X " + getLength();
    }
}

1 回答

  • 1

    好吧,没有名为 equals() 的静态方法,并且在 TestNew 类中有2个参数 . 这就是编译器告诉你的 . 为了能够调用方法,该方法必须存在 .

相关问题