*13.11 (The Octagon class) Write a class named Octagon that extends GeometricObject and implements the Comparable and Cloneable interfaces. Assume that all eight sides of the octagon are of equal length. The area can be computed using the following formula: area = (2 + 4/22)* side * side Draw the UML diagram that involves Octagon, GeometricObject, Comparable, and Cloneable. Write a test program that creates an Octagon object with side value 5 and displays its area and perimeter. Create a new object using the clone method and compare the two objects using the compareTo method.
uml图
源码:
父类——几何图形抽象类
package experiment06;
public abstract class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
protected GeometricObject() {
dateCreated = new java.util.Date();
}
protected GeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
public java.util.Date getDateCreated() {
return dateCreated;
}
public String toString() {
return "created on " + dateCreated.toLocaleString() + "\ncolor: " + color + " and filled: " + filled;
}
public abstract double getArea();
public abstract double getPerimeter();
}
八边形实体类继承几何图形实现比较接口和克隆接口:
package experiment06;
/**
* 八边形实体类
*/
public class Octagon extends GeometricObject implements Comparable<Octagon>, Cloneable {
private double side;// 八边形边长
// 构造方法
public Octagon(double side) {
super();
this.side = side;
}
@Override
public int compareTo(Octagon o) {
return (int) (getArea() - o.getArea());
}
@Override
public double getArea() {
return (2 + 4 / Math.sqrt(2)) * side * side;
}
@Override
public double getPerimeter() {
return 8 * side;
}
@Override
protected Octagon clone() throws CloneNotSupportedException {
return (Octagon) super.clone();
}
@Override
public String toString() {
return "八边形 [边长side=" + side + ", 面积=" + getArea() + ", 周长=" + getPerimeter() + "]";
}
}
测试类 new一个边长为5的正八边形并克隆 再与克隆体比较
package experiment06;
public class TestOctagon {
public static void main(String[] args) throws CloneNotSupportedException {
Octagon octagon1 = new Octagon(5);
System.out.println(octagon1);
Octagon octagon2 = octagon1.clone();
int result = octagon1.compareTo(octagon2);
System.out.println("两八边形比较结果为:\n"+(result==0?"一模一样":"有所不同"));
}
}
运行截图