Home > DeveloperSection > Interviews > What is Inheritance in C#

Posted on    May-04-2016 7:23 AM

 C# C#  OOPS  Inheritance 
Ratings:
 1 Answer(s)
  335  View(s)
Rate this:

Simond Gear
Simond Gear

Total Post:2

Points:10
Posted on    May-04-2016 7:23 AM

Inheritance:

 

Inheritance is the ability to define a new class or object that inherits the behavior and its functionality of an existing class. The new class or object is called a child or subclass or derived class while the original class is called parent or base class.

 

In other words when a class acquire the property of another class is known as inheritance.We can say that, inheritance is the second pillar of OOPs because with the help of single class we can’t make our project.  Through inheritance we can achieve code reusability and encapsulation.

 For example, I have created a Shape class as a Parent class

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OopsConcepts
{
    class Shape
    {
        protected int width;
        protected int height;     
        public void setWidth(int w)
        {
            width = w;
        }
        public void setHeight(int h)
        {
            height = h;
        }    
    }
}

 

  Here I have creating an another class Rectangle that inherit to Shape class

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 
namespace OopsConcepts
{
    class Rectangle:Shape
    {
        public int getArea()
        {
            return(width * height);
        }
        public int getPerimeter()
        {
            return2*(width + height);
        }      
    }
}
 


And create another entry point class (RectangleTest) and which we are creating object of the Rectangle class for calling the method of their respective class.


using System;                                                                                   
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OoopsConcepts
{
    class RectangleTest
    {
        static void Main(string[] args)
        {
            // Inhertance Test          
            Rectangle rectange = new Rectangle();           rectangle.setWidth(10);
            rectangle.setHeight(5);
            Console.WriteLine("Total area : {0}", rectangle.getArea());
            Console.WriteLine("Perimeter : {0}", rectangle.getPerimeter());
            Console.ReadLine();
}
}
}

 

Output:

Total area: 50

Perimeter:  30

 


Modified On Aug-05-2016 01:25:42 AM

Don't want to miss updates? Please click the below button!

Follow MindStick