Tuesday, 23 August 2011

Inheritance and Polymorphism tips


The following example is demonstrated in C#

I have classB inherites from classA as following:

    class Program
    {
        static void Main(string[] args)
        {
            classB b = new classB();
            classA a = b as classA;
            a.DoSomething();
            b.DoSomething();

            classB b2 = a as classB;
            b2.DoSomethingElse();
        }
        public class classA
        {
            protected string s = "hello from classA";

            public classA()
            {
                s = "hello from classA";
            }

            public void DoSomething()
            {
                Console.WriteLine(s);
            }
        }
        public class classB : classA
        {
            protected string d = "something else";

            public classB()
            {
                s = "hello from classB";
            }
            public void DoSomethingElse()
            {
                Console.WriteLine(d);
            }
        }
    }

The derived class - classB gains all the non-private data and behavior of the base class (classA) in addition to any other data or behaviors it defines for itself. classB is effectively both classB and classA (polymorphism).

When the program is run, both a.DoSomething() and b.DoSomething() output "hello from classB" to the Console, because when creating classB object, the Constructor of classA will be called before the Constructor of classB is called, so the value of s is "hello from classB".

When classB is cast to classA, classB is not changed by the cast, but the view of classB becomes restricted to classA's data and behavior. After casting classB to classA, that classA can be cast back to classB without losing the data. So when b2.DoSomethingElse() is invoked, it will output "something else"

No comments:

Post a Comment