Monday, 25 September 2017

Inheritance In C#

When you derive a class from a base class, the derived class will inherit all members of the base class except constructors, though whether the derived class would be able to access those members would depend upon the accessibility of those members in the base class. C# gives us polymorphism through inheritance. Inheritance-based polymorphism allows us to define methods in a base class and override them with derived class implementations. Thus if you have a base class object that might be holding one of several derived class objects, polymorphism when properly used allows you to call a method that will work differently according to the type of derived class the object belongs to.
The Following are the classes


class Animal
{
    public Animal()
    {
        Console.WriteLine("Animal constructor");
    }
    public void Greet()
    {
        Console.WriteLine("Animal says Hello");
    }
    public void Talk()
    {
        Console.WriteLine("Animal talk");
    }
    public virtual void Sing()
    {
        Console.WriteLine("Animal song");
    }
}; 
Now Try this one
 
class Dog : Animal
{
    public Dog()
    {
        Console.WriteLine("Dog constructor");
    }
    public new void Talk()
    {
        Console.WriteLine("Dog talk");
    }
    public override void Sing()
    {
        Console.WriteLine("Dog song");
    }
}; 
Now call above methods
Animal a1 = new Animal();
a1.Talk();
a1.Sing();
a1.Greet();

//Output

Animal constructor
Animal talk
Animal song
Animal says Hello
Okay Now call this one
Animal a2 = new Dog();
a2.Talk();
a2.Sing();
a2.Greet();

//Output

Animal constructor
Dog constructor
Animal talk
Dog song
Animal says Hello

No comments:

Post a Comment