编写一个名为Octagon的类,它扩展Geometricobject类并实现Comparable,Cloneable接口。假设八边形八条边的边长都相等。它的面积可以用下面的公式计算: 面积=(2+4

    xiaoxiao2021-04-15  353

    题目 编写一个名为Octagon的类,它扩展Geometricobject类并实现Comparable,Cloneable接口。假设八边形八条边的边长都相等。它的面积可以用下面的公式计算: 面积=(2+4/sqrt(2))边长边长 画出Octagon、Geometricobject、Comparable,Cloneable的UML图。编写一个测试程序,创建一个边长值为5的Octagon对象,然后显示它的面积和周长。使用clone方法创建一个新对象,并使用compareTo方法比较这两个对象。代码 package testoctagon; /** * 1. @author shinan */ abstract class Geometricobject{ String color="white"; boolean filled; java.util.Date dateCreated; public Geometricobject(){ dateCreated=new java.util.Date(); } public 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 abstract double getArea(); public abstract double getPerimeter(); } class Octagon extends Geometricobject implements Comparable,Cloneable{ double side=0; public Octagon(double side){ this.side=side; } public double setSide(){ return side; } public double getArea(){ return side*side*(2+4/Math.sqrt(2)); } public double getPerimeter(){ return side*8; } public Object clone()throws CloneNotSupportedException{ return super.clone(); } public int compareTo(Object o){ if(getArea()>((Octagon)o).getArea()) return 1; else if (getArea()<((Octagon)o).getArea()) return -1; else return 0; } } public class TestOctagon { /** * @param args the command line arguments */ public static void main(String[] args)throws Exception{ // TODO code application logic here Octagon o=new Octagon(5); System.out.println(o.getArea()); System.out.println(o.getPerimeter()); //Octagon a=new Octagon(4); //Octagon a1=a; Octagon a2=(Octagon)o.clone(); System.out.println(o.compareTo(a2)); } }

    运行结果截图

    UML图


    最新回复(0)