OOPS


class A
    {
        public void Display()
        {
            Console.WriteLine("class A display");
        }
    }

    class B : A
    {
        public void Display()
        {
            Console.WriteLine("class B display");
        }
        public void Print()
        {
            Console.WriteLine("class B print");
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
            A obj = new B();
            obj.Display();  // will call method of class A. why?

            Console.ReadLine();
        }

    }


OutPut :  class A display


Explanation:
When we extend class A into class B, it will inherit all its methods and properties. So, in this case, obj is the instance variable of class A
but containing the newly created object of class B. So what happens is, after executing the line, obj now contains the methods of both classes i.e, class A as well as class B. but, when we call any method only class A methods will be called because reference of class A only is saved in obj.

Comments

  1. If we override the Class B's method then it will get executed B's Method

    ReplyDelete

Post a Comment

Popular posts from this blog

iframe vs embed vs object in HTML 5

Constructor in c#

What is the need of method overriding ???