Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   Inheritance & Polymorphism (http://www.go4expert.com/articles/inheritance-polymorphism-t1468/)

shabbir 25Sep2006 15:09

Inheritance & Polymorphism
 

Background



As in other langauges 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 a new dimension to us through inheritance.

Moving on ...



Consider the following class which we'll use as a base class.

Code: CSharp

class Base
{
    public Base()
    {
        Console.WriteLine("Base class constructor");
    }

    public void Func1()
    {
        Console.WriteLine("Base class Func1");
    }

    public void Func2()
    {
        Console.WriteLine("Base class Func2");
    }

    public virtual void Func3()
    {
        Console.WriteLine("Base class Func3");
    }
}

Now lets derive a class from the above class.
Code: CSharp

class Derived : Base
{
    public Derived()
    {
        Console.WriteLine("Derived class constructor");
    }

    public void Func1()
    {
        Console.WriteLine("Derived class Func1");
    }

    public new void Func2()
    {
        Console.WriteLine("Derived class Func2");
    }

    public override void Func3()
    {
        Console.WriteLine("Derived class Func3");
    }
}

Now try the following program
Code: CSharp

Base b = new Base();
b.Func1();
b.Func2();
b.Func3();

Base d = new Derived();
d.Func1();
d.Func2();
d.Func3();

Output looks like
Code:

Base class constructor
Base class Func1
Base class Func2
Base class Func3
Base class constructor
Derived class constructor
Base class Func1
Base class Func2
Derived class Func3

Base class output is as expected but the derived class has some unexpected output. Now look at the function signatures of Func1, Func2, Func3 in the base class first. Func1 and Func2 has public void where as Func3 has public virtual void. By making any function virtual you allow it to be derived in the derived classes but the functions not defined with virtual will not be derived. If you change the Base class type "d" to Derived class d Derived d = new Derived(); then you will see the output as follows.
Code:

Base class constructor
Derived class constructor
Derived class Func1
Derived class Func2
Derived class Func3

The Derived Func2 has the prototype as public new void which means that actually its not overriding the Func2 method but overwriting the Func2 Method and hiding the base class implementation with its own function.


All times are GMT +5.5. The time now is 17:57.