In: Computer Science
**Java** - Creating from scratch. Original code hasn't been created yet.
Design a class named Octagon that extends
GeometricObject class and implements the Comparable and
Cloneable interface. Assume that all eight sides of the octagon are
of equal size. The area can be computed using following
formula:
Write a test program that creates an Octagon object with
side values 5 and display its area and perimeter. Create a new
object using clone method and compare the two objects using
compareTo method.
Java code:
Octagon.java:
public class Octagon extends GeometricObject implements Cloneable, Comparable<Octagon> { private double side; public Octagon(double side) { this.side = side; } public double getSide() { return side; } public void setSide(double side) { this.side = side; } //Returns the area of the Octagon; area formula: 2*(1+/√2)* side * side public double getArea() { return 2 * (1 + Math.sqrt(2)) * getSide() * getSide(); } //Returns the pertmeter of the Octagon; perimeter formula: 8*side public double getPerimeter() { return 8 * getSide(); } @Override public int compareTo(Octagon o) { if (getArea() > o.getArea()) return 1; else if (getArea() < o.getArea()) return -1; else return 0; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } //Testing octagon public static void main(String[] args) throws CloneNotSupportedException { //creates an Octagon object with side values 5 Octagon octagon1 = new Octagon(5); System.out.println("Area: " + octagon1.getArea() + "; Perimeter: " + octagon1.getPerimeter()); // creates a new object using clone method Octagon octagon2 = (Octagon) octagon1.clone(); //compares the two objects using compareTo method System.out.println(octagon1.compareTo(octagon2) == 0 ? "They are same" : "They are not same"); } }
GeometricObject.java:
public abstract class GeometricObject { private String color = "while"; private boolean filled; /** Construct a geometric object with color and filled value */ protected GeometricObject(String color, boolean filled) { this.color = color; this.filled = filled; } public GeometricObject() { } /** Return color */ public String getColor() { return color; } /** Set a new color */ public void setColor(String color) { this.color = color; } /** Return filled. Since filled is boolean, * the get method is named isFilled */ public boolean isFilled() { return filled; } /** Set a new filled */ public void setFilled(boolean filled) { this.filled = filled; } /** Abstract method getArea */ public abstract double getArea(); /** Abstract method getPerimeter */ public abstract double getPerimeter(); }
Output:
Area: 120.71067811865476; Perimeter: 40.0
They are same