Thursday, 26 July 2012

Inheritance in C#


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");
    }
};

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");
    }
};

Animal a1 = new Animal();
a1.Talk();
a1.Sing();
a1.Greet();



Dog d1 = new Dog();
d1.Talk();
d1.Sing();
d1.Greet();



class Color
{
    public virtual void Fill()
    {
        Console.WriteLine("Fill me up with color");
    }
    public void Fill(string s)
    {
        Console.WriteLine("Fill me up with {0}",s);
    }
};

Color c1 = new Color();
c1.Fill();
c1.Fill("red");


class Green : Color
{
    public override void Fill()
    {
        Console.WriteLine("Fill me up with green");
    }
};


Green g1 = new Green();
g1.Fill();
g1.Fill("violet");

//Output
Fill me up with green
Fill me up with violet


class Software
{
    public Software()
    {
        m_x = 100;
    }
    public Software(int y)
    {
        m_x = y;
    }
    protected int m_x;
};

class MicrosoftSoftware : Software
{
    public MicrosoftSoftware()
    {
        Console.WriteLine(m_x);
    }
};


MicrosoftSoftware m1 = new MicrosoftSoftware();



class DundasSoftware : Software
{
     
    public DundasSoftware(int y) : base(y)
    {
        Console.WriteLine(m_x);
    }
   
    //Here we are telling the compiler to first
    //call the other overload of the constructor
    public DundasSoftware(string s, int f) : this(f)
    {
        Console.WriteLine(s);
    }
};


No comments:

Post a Comment