I am trying to learn polymorphism and I am building a Shape hierarchy where a Shape class has two children namely TwoDimensionalShape and ThreeDimensionalShape. Again the TwoDimensionalShape has Circle, Square as children and ThreeDimensionalShape has Sphere, Cube as children. Here is my code till now.
public abstract class Shape
{
public abstract double area();
}
public abstract class TwoDimensionalShape : Shape
{
public abstract override double area();
}
public abstract class ThreeDimensionalShape : Shape
{
public abstract override double area();
public abstract double volume();
}
And I created Circle and Square classes under TwoDimensionalShape where I implemented the area method. Also I created Sphere and Cube classes under ThreeDimensionalShape where I implemented both area and volume methods. In my main method, I am trying to do this.
Shape[] myShapes = new Shape[4];
myShapes[0] = new Circle(4.0);
myShapes[1] = new Square(2.0);
myShapes[2] = new Sphere(8.0);
myShapes[3] = new Cube(6.0);
for (int i = 0; i < myShapes.Length; i++)
{
Console.Write(myShapes[i].ToString());
if(myShapes[i] is TwoDimensionalShape)
Console.WriteLine(" : Area = {0}", myShapes[i].area());
else if (myShapes[i] is ThreeDimensionalShape)
{
Console.Write(" : Area = {0}", myShapes[i].area());
Console.WriteLine(" : Volume = {0}", myShapes[i].volume());
}
}
Now I am getting an error that my Shape class does not contain any definition for 'volume'. So where do I put this volume method? I think I should put it in the Shape base class itself, but volume method is only specific to 3D Shapes right? Also why am I getting this error? I am only calling the volume method if myShapes[i] is ThreeDimensionalShape.
So where exactly should my volume method be?