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:15 | ISBN:9780136091813 | Edition: 2

Question

Write a class named Hexagon whose objects represent regular hexagons (6-sided polygons). Your class should implement the Shape interface defined in this chapter.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package inheritance;

// the Hexagon class implemetns the Shape interface
public class Hexagon implements Shape {

	double sideLength;

    // create constructor which takes the sidelength as argument
	public Hexagon(double sideLength) {

		this.sideLength = sideLength;
	}

    // below method return the area Hexagon
	@Override
	public double getArea() {

		return ((Math.sqrt(3) * 3) / 2) * sideLength * sideLength;
	}

	@Override
	public double getPerimeter() {

		return 6 * sideLength;
	}

	public static void main(String args[]) {

		Hexagon hex = new Hexagon(6);

		System.out.println("Area of hexagon is: " + hex.getArea());
		System.out.println("Perimeter of hexagon is: " + hex.getPerimeter());

	}

}
Output:

Area of hexagon is: 93.53074360871938
Perimeter of hexagon is: 36.0

 

0 0

Discussions

Post the discussion to improve the above solution.