Write a class named Octagon whose objects represent regular octagons (eight-sided polygons). Your class should implement the Shape interface defined in this chapter, including methods for its area and perimeter. An Octagon object is defined by its side length. (You may need to search online to find formulas for the area and perimeter of a regular octagon.)
package inheritance; public class Octagon implements Shape { double sideLength;
// constructs a new Octagon with the given sidelengthpublic Octagon(double sideLength) { this.sideLength = sideLength; } // get area method return the area of Octagon @Override public double getArea() { return 2 * (1 + Math.sqrt(2)) * sideLength * sideLength; } @Override public double getPerimeter() { return 8 * sideLength; } public static void main(String args[]) { // initalize the new Octagon object Octagon hex = new Octagon(6); System.out.println("Area of hexagon is: " + hex.getArea()); System.out.println("Perimeter of hexagon is: " + hex.getPerimeter()); } }
Output:
Area of hexagon is: 173.82337649086284
Perimeter of hexagon is: 48.0