CSharp - Get to know Inheritance

Introduction

A class can inherit from another class.

Inheriting from a class can reuse the functionality in that class.

A class can inherit from only a single class.

A derived class is also called a subclass. A base class is also called a superclass.

Example

The following code defines a class called Shape:

class Shape
{
       public string Name;
}

Next, we define classes called Circle and Square, which will inherit from Shape.

Circle and Square get everything an Shape has, plus any additional members that they define:

class Circle : Shape   // inherits from Shape
{
       public long Radius;
}

class Square : Shape   // inherits from Shape
{
       public decimal Width;
}

Here's how we can use these classes:

Demo

using System;
class MainClass//from   w  w w .  j a v a 2 s . com
{
   public static void Main(string[] args)
   {
         Circle myCircle = new Circle { Name="MyCicle", Radius=1000 };
    
         Console.WriteLine (myCircle.Name);    // MyCicle
         Console.WriteLine (myCircle.Radius);  // 1000
    
         Square mySquare = new Square { Name="MySquare", Width=250000 };
    
         Console.WriteLine (mySquare.Name);   // MySquare
         Console.WriteLine (mySquare.Width);  // 250000
   }
}
class Circle : Shape   // inherits from Shape
{
       public long Radius;
}

class Square : Shape   // inherits from Shape
{
       public decimal Width;
}
class Shape
{
       public string Name;
}

Result

The derived classes, Circle and Square, inherit the Name property from the base class, Shape.

Related Topics