Java(八边形类0ctagon)编写一个名为0ctagon 的类,它继承自Geometricobject类并实现Comparable 和Coneable 接口。假设八边形八条边的边长都相等。它的面积可以使用下面的公式计算: 面积=(2+4/√2)x边长x 边长 画出包括0ctagon、GeometricObject、Comparable和Cloneable的UML图。编写一个测试程序,创建一个边长值为5的0tagon 对象,然后显示它的面积和周长。使用clone 方法创建一个新对象,并使用 compareTo 方法比较这两个对象。
时间: 2024-02-23 21:59:11 浏览: 129
好的,下面是您要求的Octagon类的代码和UML图:
```java
public class Octagon extends GeometricObject implements Comparable<Octagon>, Cloneable {
private double side;
public Octagon(double side) {
this.side = side;
}
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
@Override
public double getArea() {
return (2 + 4 / Math.sqrt(2)) * side * side;
}
@Override
public double getPerimeter() {
return 8 * side;
}
@Override
public int compareTo(Octagon o) {
if (this.getArea() > o.getArea()) {
return 1;
} else if (this.getArea() < o.getArea()) {
return -1;
} else {
return 0;
}
}
@Override
public Octagon clone() {
Octagon o = new Octagon(this.side);
return o;
}
}
```
UML图如下:
```
GeometricObject
+color: String
+filled: boolean
+GeometricObject()
+GeometricObject(color: String, filled: boolean)
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+getArea(): double
+getPerimeter(): double
|
|
v
Comparable
+compareTo(o: Object): int
|
|
v
Cloneable
+clone(): Object
|
|
v
Octagon
+side: double
+Octagon(side: double)
+getSide(): double
+setSide(side: double): void
+getArea(): double
+getPerimeter(): double
+compareTo(o: Octagon): int
+clone(): Octagon
```
接下来是测试程序:
```java
public class Test {
public static void main(String[] args) {
Octagon o1 = new Octagon(5);
System.out.println("Octagon 1:\nArea = " + o1.getArea() + "\nPerimeter = " + o1.getPerimeter());
Octagon o2 = o1.clone();
int result = o1.compareTo(o2);
if (result > 0) {
System.out.println("Octagon 1 is larger than Octagon 2");
} else if (result < 0) {
System.out.println("Octagon 1 is smaller than Octagon 2");
} else {
System.out.println("Octagon 1 is equal to Octagon 2");
}
}
}
```
输出结果为:
```
Octagon 1:
Area = 120.71067811865476
Perimeter = 40.0
Octagon 1 is equal to Octagon 2
```
其中,Octagon 2 是用 clone 方法创建的一个新的 Octagon 对象。由于两个对象的面积相等,所以 compareTo 方法返回值为 0。
阅读全文