Answer to Question #248529 in C# for shaves

Question #248529

1.     Define abstract class Shape with only one virtual method CalculateSurface() and fields width and height. Define two new classes Triangle and Rectangle that implement the virtual method and return the surface of the figure (height*width for rectangle and height*width/2 for triangle). Define class Circle and suitable constructor so that on initialization height must be kept equal to width and implement the CalculateSurface() method. Write a program that tests the behavior of the CalculateSurface() method for different shapes (Circle, Rectangle, Triangle) stored in an array.



1
Expert's answer
2021-10-08T17:10:12-0400
using System;


namespace App
{
    class Program
    {
        abstract class Shape
        {
            public double width;
            public double height;
            public virtual double CalculateSurface() {
                return 0;
            }
        }


        class Rectangle : Shape
        {


            public override double CalculateSurface()
            {
                return height * width;
            }
        }
        class Triangle : Shape
        {


            public override double CalculateSurface()
            {
                return height * width / 2;
            }
        }
        class Circle : Shape
        {


            public Circle(double radius)
            {
                this.height = radius;
                this.width = radius;
            }


            public override double CalculateSurface()
            {
                return Math.PI * height * width;
            }
        }




        static void Main(string[] args)
        {
            Shape[] shapes = new Shape[3];
            shapes[0] = new Rectangle();
            shapes[0].height = 5;
            shapes[0].width = 4;


            shapes[1] = new Triangle();
            shapes[1].height = 5;
            shapes[1].width = 4;


            shapes[2] = new Circle(5);




            for (int i = 0; i < 3; i++) {
                Console.WriteLine("Surface: {0}", shapes[i].CalculateSurface());
            }


                Console.ReadLine();
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS