(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 following formula
Area = (2+4/√2) * side * side
Write a Test program that creates an
Octagon
object with side value 5 and displays its area and perimeter. Create a new object using
clone
method and compare the two objects using
compareTo
method.
Otagon
public class Octagon extends GeometricObject implements Comparable<Octagon>, Cloneable {
private double side;
public Octagon() {
}
public Octagon(double side) {
this.side = side;
}
//get method
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
public double getArea() {
return (2 + (4 / (Math.sqrt(2))) * side * side);
}
public double getPerimeter() {
return side * 8;
}
public String toString() {
return "Area: " + getArea() + "\nPerimeter: "
+ getPerimeter() + "\nClone Compare: " + "\nFirst Compare: ";
}
public int compareTo(Octagon octagon) {
if(getArea() > octagon.getArea())
return 1;
else if(getArea() < octagon.getArea())
return -1;
else
return 0;
}
// clone method
public Octagon clone() {
return new Octagon(this.side);
}
}
GeometricObject
public abstract class GeometricObject {
public abstract double getArea();
public abstract double getPerimeter();
}
OtagonTesing
import java.util.*;
public class OctagonTesing {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("Homework.dat" );
Scanner fin = new Scanner(file);
Octagon first = null;
int i = 1;
Octagon older;
while(fin.hasNext())
{
double side = fin.nextDouble();
if(side < 0.0)
break;
Octagon oct = new Octagon(side);
System.
out
.print("Octagon " + i + ": \"" + oct.toString() + "\"");
if (first == null) {
first = oct;
System.
out
.print("Equal");
}
else {
int comparison = oct.compareTo(first);
if (comparison < 0)
System.
out
.print("less than first");
else if (comparison > 0)
System.
out
.print("greater than first");
else
System.
out
.print("equal");
}
//using clone method to compare
String cloneComparison = "Clone Compare: ";
older = oct;
Octagon clone = oct.clone();
if ( older.getArea() == clone.getArea() ){
cloneComparison = cloneComparison + "Equal";
} else {
cloneComparison = cloneComparison + "Not Equal";
}
//System.out.println(cloneComparison);
i++;
first = new Octagon(side);
System.
out
.println();
}
fin.close();
}
}