Tuesday, August 2, 2016

Parent obj = new child() c# (Polymorphism)

public class A
    {
        public A()
        {
            Console.WriteLine("A");
        }
        public virtual void method()
        {
            Console.WriteLine("AM");
        }

    }
    public class B : A
    {
        public B()
        {
            Console.WriteLine("B");

        }
        public new void method()
        {
            Console.WriteLine("BM");

        }
    }

      Always Declare Behind (Parent) 1st

B obj = new A(); X
A obj = new B(); output A B AM, because linking to virtual A method. New void or normal void also is this result

B obj = new B(); output A B BM, direct call B method

A < B = B is A (Child is Parent)
Child obj = new Parent() is not possible, Parent is not Child

If change to public override void method()
All output is A B BM

Why want call like this? Why not call A obj = new A();
Because you want to use all these child classes through the interface / methods defined on your parent class.
·
http://www.akadia.com/services/dotnet_polymorphism.html
http://www.codeproject.com/Articles/816448/Virtual-vs-Override-vs-New-Keyword-in-Csharp

No comments:

Post a Comment