SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Inheritance And Interfaces
Exercise:
Exercises
Question:14 | ISBN:9780136091813 | Edition: 2

Question

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.)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package inheritance;

public class Octagon implements Shape {

	double sideLength;

    // constructs a new Octagon with the given sidelength
	public 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

 

0 0

Discussions

Post the discussion to improve the above solution.