To represent a regular hexagon in Java, create a class named Hexagon with attributes and methods for side length, area calculation, and comparison. A TestHexagon class will be used to demonstrate the functionality of Hexagon instances with different scenarios.
Designing a Hexagon Class in Java
To represent a regular hexagon in Java, you can create a class named Hexagon with various attributes and methods. Below is an outline of the class design:
a.A double data field/attribute named side to hold the length of the hexagon's sides.
b.A no-arg constructor that initializes the side to a default value of 1.
c.A constructor that accepts a single parameter to specify the side of the hexagon.
d.A method named getArea() that computes and returns the area of the hexagon using the formula 3/2 * √3 * side * side.
e.A mutator method to change the side of the hexagon.
f.An accessor method to get the current value of the side attribute.
g.A toString method that returns a string containing the side and the area of the hexagon.
h.An equals method that compares two hexagons' areas to determine if they are equal.
i.TestHexagon Class with Main Method
j.The TestHexagon class will have a main method to create hexagon instances, and perform the following actions:
1.Create an instance of Hexagon using the default constructor, hex1.
2.Create another instance, hex2, with a specified side value of 4.5.
3.Output the areas of hex1 and hex2.
4.Set the side of hex1 to match that of hex2 and output the information using toString() method.
5.Compare hex1 and hex2 using the equals method and output the results.
6.Modify hex2's side to 6.3 and compare again with hex1.