java - 我需要使用可比较的界面比较两个形状以确定哪个大于或小于另一个
问题描述
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() 方法,并让它返回一个包含当前对象名称及其区域的字符串,格式如下:
名称:区域
我只是需要一些指导
解决方案
int compareTo(Shape shape) {
return getArea() - shape.getArea();
}
这将允许您比较形状,如果它更小,该方法将返回 <0,如果相等则返回 0,如果它具有更大的正数,就像 Comparable 接口应该做的那样
推荐阅读
- node.js - 在 Nodejs 中使用 Unirest 将图像保存到文件
- c# - 如何通过 Web API 使用 AntiXss
- go - Go 扫描缓冲区有时会挂起
- mysql - 在排除某些客户的同时寻找具有相似口味的客户
- android - 一项活动中的多个回收商意见
- list - 扫雷板标签(初级)
- neo4j - 使用 py2neo 进行 Neo4j 可视化:TypeError: 'LabelSetView' object is not callable
- excel - VBA - 尝试从组合框中删除项目时出现错误 381
- unit-testing - KotlinTest 基于属性的测试和生成器
- python - Google Colab 不显示图片