Saturday, 7 May 2011

Concepts of Inheritance in C#

Inheritance:
  In C#, the specialization relationship is generally implemented by using inheritance. Inheritance is also provides the reusability,  or we can say that extracts some features from one class to another class.

class Bird
{
    public Bird()
    {
        Console.WriteLine("Bird constructor");
    }
    public void Greet()
    {
        Console.WriteLine("Bird says Hello");
    }
    public void Talk()
    {
        Console.WriteLine("Bird talk");
    }
    public virtual void Sing()
    {
        Console.WriteLine("Bird song");
    }
}
class Peacock : Bird
{
    public Peacock()
    {
        Console.WriteLine("Peacock constructor");
    }
    public new void Talk()
    {
        Console.WriteLine("Peacock talk");
    }
    public override void Sing()
    {
        Console.WriteLine("Peacock song");
    }
}
Bird a1 = new Bird();
a1.Talk();
a1.Sing();
a1.Greet();

Bird a2 = new Peacock();
a2.Talk();
a2.Sing();
a2.Greet();
Types of Inheritance:
In Object Oriented Programming concept there are 3 types of inheritances.
1. Single Inheritance,
2. Multiple Inheritance
3. Multilevel Inheritance


Single Inheritance:

public class A
{
}
public class B:A
{
}


Multiple Inheritance:

public class A
{
}
public class B
{
}
public class C:A,B
{
}



Multilevel Inheritance:
public class A
{
}
public class B:A
{
}
public class C:B
{
}

In the above three types C# don't proved Multiple Inheritance. As there is conflict of multiple override methods in base classes (say A, B in above example) As in Place C# give another feature called Interfaces using interfaces you can achieve multiple Inheritance feature.

Polymorphism
Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details.
Creating Polymorphic Types:
 
For creating polymorphism there are two steps-
1. Create a base class with virtual methods.
2. Create derived classes that override the behavior of the base class’s virtual methods.

 To create a method in a base class that supports polymorphism, mark the method as virtual.
Example.

public class BaseClass
{
    public virtual void DoWork() 
    { 
 }
    public virtual int WorkProperty
    {
        get {
     return 0;
            }
    }
}
public class DerivedClass : BaseClass
{
    public override void DoWork() 
     {
 
     }
    public override int WorkProperty()
    {
        get {
      return 0; 
     }
    }
}

No comments:

Post a Comment