--JAVA PROGRAM-- Write a class named Octagon that extends GeometricObject and im
ID: 3680280 • Letter: #
Question
--JAVA PROGRAM--
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: (2 + (4/sqrt(2))) * side * side
Write a test program that creates an Octagon object with side value 9 and displays its area and perimeter. Create a new object using the clone method and compare the two objects using the compareTo method.
Expected results:
Area is 391.10
Perimeter is 72.0
Compare objects (equals: 0): 0
Explanation / Answer
Below is the program. Formula for calculating octagon area is given wrong. So I have corrected it
abstract class GeometricObject {
public abstract double getArea();
public abstract double getPerimeter();
}
class Octagon extends GeometricObject implements Comparable<Octagon>, Cloneable {
private double side;
public Octagon(double side) {
this.side = side;
}
public double getArea() {
// return (2 + (4 / (Math.sqrt(2))) * side * side);
//formula provided in the question is wrong,so corrected it
return (2 * (1+ (Math.sqrt(2))) * side * side);
}
public double getPerimeter() {
return side * 8;
}
public int compareTo(Octagon octagon) {
if(getArea() > octagon.getArea())
return 1;
else if(getArea() < octagon.getArea())
return -1;
else
return 0;
}
public Octagon clone(){
return new Octagon(this.side);
}
public String toString() {
return "Area: " + getArea() + " Perimeter: "
+ getPerimeter();
}
}
public class TestOctagon
{
public static void main(String[] args)
{
Octagon oct = new Octagon(9);
System.out.println("Octagon of side 9: "" + oct.toString() + """);
Octagon clone = oct.clone();
int comparison = oct.compareTo(clone);
if (comparison < 0)
System.out.print("less than first");
else if (comparison > 0)
System.out.print("greater than first");
else
System.out.print("equal");
System.out.println(" ");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.