Abhilash J A

Abhilash J A

  • 530
  • 2.4k
  • 598.3k

When to use Inheritance in C#?

Sep 12 2016 2:13 AM
Hello everyone,
 
Kindly explain "What is the use of Inheritance? and When to use?"  with respect two below programs. 
 
Why I cannot get output from 1st program after using class initialization?
 
Program 1:
 
 
  1. class Program  
  2.    {  
  3.        class Shape  
  4.        {  
  5.            public void setWidth(int w)  
  6.            {  
  7.                width = w;  
  8.            }  
  9.            public void setHeight(int h)  
  10.            {  
  11.                height = h;  
  12.            }  
  13.            public int width;  
  14.            public int height;  
  15.        }  
  16.   
  17.        // Derived class  
  18.        class Rectangle  
  19.        {  
  20.            Shape objshape = new Shape();  
  21.            public int getArea()  
  22.            {  
  23.                return (objshape.width * objshape.height);  
  24.            }  
  25.        }  
  26.        static void Main(string[] args)  
  27.        {  
  28.            Shape Rect = new Shape();  
  29.            Rectangle objRectangle = new Rectangle();  
  30.            Rect.setWidth(5);  
  31.            Rect.setHeight(7);  
  32.   
  33.            // Print the area of the object.  
  34.            Console.WriteLine("Total area: {0}", objRectangle.getArea());  
  35.            Console.ReadKey();  
  36.        }  
  37.    }  
 
 Program 2:
 
  1. class Program  
  2.    {  
  3.        class Shape  
  4.        {  
  5.            public void setWidth(int w)  
  6.            {  
  7.                width = w;  
  8.            }  
  9.            public void setHeight(int h)  
  10.            {  
  11.                height = h;  
  12.            }  
  13.            public int width;  
  14.            public int height;  
  15.        }  
  16.   
  17.        // Derived class  
  18.        class Rectangle : Shape  
  19.        {  
  20.            public int getArea()  
  21.            {  
  22.                return (width * height);  
  23.            }  
  24.        }  
  25.        static void Main(string[] args)  
  26.        {  
  27.            Rectangle Rect = new Rectangle();  
  28.   
  29.            Rect.setWidth(5);  
  30.            Rect.setHeight(7);  
  31.   
  32.            // Print the area of the object.  
  33.            Console.WriteLine("Total area: {0}", Rect.getArea());  
  34.            Console.ReadKey();  
  35.        }  
  36.    }  
 

Answers (1)