February 19, 2011

Inheritance Example C#

*Create a class called Circle that contains calculations for a circle based on its radius. It calculates the
*Diameter,
*Circumference,
*Area.
*
*Then Create a class called Sphere inherits from the Circle class and calculates below based on its radius.
*Area
*Volume
 
*Get Below calculations for both the Circle and sphere
*Diameter,
*Circumference,
*Area
*Get Below calculations for sphere
*Volume


Program.cs

using System;
using System.Collections.Generic;
using System.Text;


namespace ConsoleApplication1
{
    class Circle
    {
        private double _radius;


        public double Radius
        {
            get {
                if (_radius < 0)
                {
                    return 0.0;
                }
                else
                {
                    return _radius;


                }
            
            
            }
            set 
            {
                _radius = value; 
            }
        }
        public double Diameter
        {
            get { return Radius * 2; }
        }
        public double Circumference
        {
            get { return Diameter * 3.14159; }
        }
        public double Area
        {
            get { return Radius * Radius * 3.14159; }
        }
    }




    class Sphere : Circle
    {
        new public double Area
        {
            get { return 4 * Radius * Radius * 3.14159; }
        }


        public double Volume
        {
            get { return 4 * 3.14159 * Radius * Radius * Radius / 3; }
        }
    }
    class Program
    {


        void ShowCircle(Circle cObj)
        {
            Console.WriteLine("Circle ");
            Console.WriteLine("Radius: " + cObj.Radius);
            Console.WriteLine("Diameter: " + cObj.Diameter);
            Console.WriteLine("Circumference:" + cObj.Circumference);
            Console.WriteLine("Area:     " + cObj.Area);
        }


        void ShowSphere(Sphere sobj)
        {
            Console.WriteLine("Sphere");
            Console.WriteLine("Radius:     " + sobj.Radius);
            Console.WriteLine("Diameter: " + sobj.Diameter);
            Console.WriteLine("Circumference: " + sobj.Circumference);
            Console.WriteLine("Area:     " + sobj.Area);
            Console.WriteLine("Volume: " + sobj.Volume);
        }
        static void Main(string[] args)
        {
            Circle c = new Circle();
            Sphere s = new Sphere();
            Program p = new Program();


            Console.WriteLine("Enter Circle Radius");
            double circleRadius =double.Parse (Console.ReadLine() );


            Console.WriteLine("Enter Sphere Radius");
            double sphereRadius = double.Parse(Console.ReadLine());


            c.Radius = circleRadius;
            p.ShowCircle(c);






            s.Radius = sphereRadius;
            p.ShowSphere(s);
                       
        }
    }
}


Below is the o/p

No comments:

Post a Comment