Understanding Inheritance using C#

The relationship between two or more classes is termed as Inheritance in an Object – Oriented Programming language. Normally there will be one class, from which the other classes may derive.

The former class is called as Base class or super class and latter class is called as derived class. All variables and methods in the base class can be called in the derived classes, provided they are declared public or protected. In C#, classes are extended by means of : operator. Consider the figure given below

The relationship in the above figure can be expressed in C# as follows:

Listing 1

<pre style="background-color: #ffffff; margin: 0em; width: 100%; font-family: consolas,&#39;Courier New&#39;,courier,monospace; font-size: 12px">public class COMPUTER
{ 
//code goes here 
} 
class COMPAQ:COMPUTER 
{ 
//code goes here 
}
class DELL: COMPUTER 
{ 
//code goes here 
} 

C# doesn’t supports multiple inheritance. Hence, the following piece of code is illegal in C#:

Listing 2

<pre style="background-color: #ffffff; margin: 0em; width: 100%; font-family: consolas,&#39;Courier New&#39;,courier,monospace; font-size: 12px">Public class COMPUTER: COMPAQ, DELL 
{ 
//code goes here 
} 

C# introduces a new concept called Interfaces (will be discussed later), which is regarded as an alternative to Multiple Inheritance.

Sealed Classes

When a base class is declared with sealed keyword, then that class cannot be extended. This is same as final keyword in Java.

Listing 3

<pre style="background-color: #ffffff; margin: 0em; width: 100%; font-family: consolas,&#39;Courier New&#39;,courier,monospace; font-size: 12px">public sealed class Computer 
{ 
//code goes here 
} 
class COMPAQ:COMPUTER 
{ 
//Not allowed as base class is sealed 
}


Abstract Classes

Abstract class is a special type of class, which should be declared with abstract keyword. Moreover, it should contain one or more abstract methods, which should contain only method definitions. It won’t be having any method body (in the form of curly braces) like Instance and Static methods.

READ  Product Review: qlWebDS Pro

Normally, a base class is declared with abstract keyword and the derived classes should extend the abstract class and implement relevant methods. Keep in mind that only one abstract class can be extended at a time since C# won’t supports multiple inheritance. Listing 9 illustrates this concept clearly:

Listing 9

<pre style="background-color: #ffffff; margin: 0em; width: 100%; font-family: consolas,&#39;Courier New&#39;,courier,monospace; font-size: 12px">using System; 
abstract public class Absdemo 
{ 
public abstract void Show(); 
} 
class Absimp:Absdemo 
{ 
public override void Show() 
{ 
Console.WriteLine(&quot;Abstract Method Implemented&quot;); 
} 
public static void Main(string[] args) 
{ 
Absimp ai = new Absimp(); 
ai.Show(); 
} 
} 

Leave a Reply

Your email address will not be published.