Write an inheritance hierarchy of threedimensional shapes Fi
Write an inheritance hierarchy of three-dimensional shapes. First, you should create an abstract class that represents all ThreeDimensionalShapes and has methods for finding the volume and surface area of the shapes. Then, you should create three subclasses that inherit from the original class : Sphere, Cube, and Tetrahedron. Each class should have an instance variable representing the dimensions of the shape (for example, the Sphere class should have an instance variable representing its radius), and each class should properly implement the methods to find surface area and volume. (Assume the Tetrahedron class represents a regular Tetrahedron.) Test your classes in a program that asks the user which shape they\'d like to create, and what dimensions they\'d like to give it. The program should print the surface area and volume of the shape (rounded to two decimal places) before terminating.
Solution
package main;
public class ShapeTest
{
public static void main( String args[] )
{
Shape shapes[] = new Shape[ 4 ];
shapes[ 0 ] = new Circle( 22, 88, 4 );
shapes[ 1 ] = new Square( 71, 96, 10 );
shapes[ 2 ] = new Sphere( 8, 89, 2 );
shapes[ 3 ] = new Cube( 79, 61, 8 );
for ( Shape currentShape : shapes )
{
System.out.printf( \"%s: %s\",currentShape.getName(), currentShape );
if ( currentShape instanceof TwoDimensionalShape )
{
TwoDimensionalShape twoDimensionalShape =
( TwoDimensionalShape ) currentShape;
System.out.printf( \"%s\'s area is %s\ \",
currentShape.getName(), twoDimensionalShape.getArea() );
}
if ( currentShape instanceof ThreeDimensionalShape )
{
ThreeDimensionalShape threeDimensionalShape =
( ThreeDimensionalShape) currentShape;
System.out.printf( \"%s\'s area is %s\ \",
currentShape.getName(), threeDimensionalShape.getArea() );
System.out.printf( \"%s\'s volume is %s\ \",
currentShape.getName(),
threeDimensionalShape.getVolume() );
}
System.out.println();
}
}
}
