Thursday, 26 September 2013

OOP concep of Shadowing , definition with example

Shadowing is very important concept of object orient programming (OOP), used with polymorphism because it involves runtime binding of objects ( pure polymorphism), it states that : " shadowing is actually stands for hiding overridden method implementation in drived class and used the implementation of parent class with drived class object", does it make sense ??, indeed but if not follwing example will make it clear for you.
This is full testable code of shadowing implementation :


class Program
    {
        static void Main(string[] args)
        {

            Person[] listPerson = new Person[2];
            listPerson[0] = new GoodPerson();
            listPerson[1] = new BadPerson();
            foreach (Person obj in listPerson)
            {
                Console.WriteLine(obj.getCategory());
            }
            Console.WriteLine(new BadPerson().getCategory());
            Console.ReadKey();
        }

        public class Person
        {
            public virtual string getCategory(){

                return "Hi I am a person";

            }
        }

        public class GoodPerson:Person
        {
            public override string getCategory()
            {

                return "Hi I am a Good Person";

            }
        }
        public class BadPerson:Person
        {
            public new string getCategory()
            {

                return "Hi I am a Bad Person";

            }
        }

    }


The output of the program will be :

Hi I am a Good Person
Hi I am a person

The trip behind this is to use "new" keyword instead of "override" with your virtual methods and that's all.