首页 > 解决方案 > 我需要使用可比较的界面比较两个形状以确定哪个大于或小于另一个

问题描述

public abstract class Shape {
protected int height;
protected int width;


public Shape(int height, int width) {
this.height = height;
this.width = width;

}




public final void printArea() {
System.out.println("This " + getName() + " has a height of " +
height + ", a width of " + width + ", and an area of " + 
getArea() + ".");
}



public final void printPerimeter() {
System.out.println("This " + getName() + " has a height of " +
height + ", a width of " + width + ", and a perimeter of " + 
getPerimeter() + ".");
}



protected abstract String getName();
protected abstract double getArea();
protected abstract double getPerimeter();

}
}

这是我的起始代码 我还有其他三个类 Rectangle、RightTriangle 和 Square 都有代码,但我首先关注我的 shape 类,我需要实现 Comparable 接口 Comparable。然后因为get area方法在每个子类中都被覆盖了。我可以在 Shape 类中编写一个 compareTo() 方法,该方法在将任何类型的 Shape 或子类对象与任何其他对象进行比较时都能正常工作。我需要实现 compareTo() 方法。所以 public int compareTo(Shape s) 正确吗?现在比较的代码是 int k = getName().compareTo(s.getName()); . 我需要重写从 Shape 类中的 Object 继承的 toString() 方法,并让它返回一个包含当前对象名称及其区域的字符串,格式如下:

名称:区域

我只是需要一些指导

标签: javainterfacecomparable

解决方案


int compareTo(Shape shape) {
   return getArea() - shape.getArea();
}

这将允许您比较形状,如果它更小,该方法将返回 <0,如果相等则返回 0,如果它具有更大的正数,就像 Comparable 接口应该做的那样


推荐阅读