简体   繁体   中英

How to achieve polymorphism in C#

I am new to C#. I was trying to check that how polymorphism could be acheived in C# and I got confused that which one way of doing is achieving polymorphism . I am using the code given below and the output is A's method .

class A
{    
    public void Display()
    {
        Console.WriteLine("A's Method");
    }
}
class B : A
{
    public void Display()
    {
        Console.WriteLine("B's Method");
    }
}

class Polymorphism
{
    public static void Main(string[] args)
    {
        A a = new B();
        a.Display();
        Console.ReadKey();
    }
}


But when I define Display() method as given below then output Method of B is called .

class A
{    
    public virtual void Display()
    {
        Console.WriteLine("A's Method");
    }
}
class B : A
{
    public override void Display()
    {
        Console.WriteLine("B's Method");
    }
}

So By what way I am achieving Polymorphism and what is the difference between both of the way and which one should be preferable for overriding. Any help would be appreciable.

Virtual methods provide polymorphism, in that subclasses can override behavior. If you don't use virtual methods all you have are types that inherit what is defined in other types, but can't replace these inherited behaviors with new ones.

In the first case, A 's method is called because you have a reference to an A , and non-virtual methods are resolved at compile time . The B object is allowed to be referenced by an A variable because B is-a A . (Note that downcasting the object and calling the result would invoke B 's method: ((B)a).Display(); .)

In the second case, B 's method is called because the method is virtual, and virtual methods are resolved at run time , based on the actual type of the object, not the type of reference it happens to be stored in.

Simply put, Polymorphism is when you can treat a derived object as if it were an ancestor object, and have all derived functionality function correctly.

In your first example, you are hiding the ancestor method, so if you treat the derived object as an ancestor then it behaves as ancestor. This is not polymorphic.

In the second example, you are overriding the ancestor method, so when you treat the object as an ancestor it still behaves like the derived object. This is polymorphic.

While it's a simple concept, there are a lot of not so simple side-effects and conditions that go along with it. For example, see the Liskov Substitution Principle (which I won't go into here). There are other principles and theories at play as well. But, it's enough to understand that polymorphism in C# is achieved primarily via inheritance (although it can also be achieved via ducktyping with dynamic objects and with generic typing of generics).

There are also several types of polymorphism... see the Wikipedia entry for more:

http://en.wikipedia.org/wiki/Polymorphism_(computer_science)

In one case you are doing method hiding and in another you are overriding it.Don't hesitate to take help of google,you'll get very useful articles or answers.Even on SO ,you'll get many similar questions.

   class A
{    
    public void Display()
    {
        Console.WriteLine("A's Method");
    }
}
class B : A
{
    public void Display()
    {
        Console.WriteLine("B's Method");
    }
}

In the above example,you are doing shadowing or method hiding.You can get the even the same result if you use new keyword like in below code.if you use don't write override in method of child class, the method in the derived class doesn't override the method in the base class, it merely hides it.

   public new void Display()
        {
            Console.WriteLine("B's Method");
        }

The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.So to aceive overriding you have to use override keyword which you are using in second example.

Simply put, if a method is not overriding the derived method, it is hiding it.An override method provides a new implementation of a member that is inherited from a base class.

You can also check here on MSDN when to do method hiding or when to do overriding.

Based on discussion on comment section,i am attaching below code.Hope it'll help you.

    using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
             A a=new A();
             a.Display();//Parent's Method
             B b =new B();
             b.Display();//Child's Method
             **A ab = new B();
             ab.Display();//Parent's Method**
             Console.ReadKey();
             Parent parent = new Parent();
             parent.Display();//Parent's Method
             Child child = new Child();
             child.Display();//Child's Method
             **Parent ParentChild = new Child();
             ParentChild.Display();//Child's Method**
             Console.ReadKey();
        }
        class A
        {
            public virtual void Display()
            {
                Console.WriteLine("Parent's Method");
            }
        }
        class B : A
        {
            public void Display()
            {
                Console.WriteLine("Child's Method");
            }
        }

        class Parent
        {
            public virtual void Display()
            {
                Console.WriteLine("Parent's Method");
            }
        }
        class Child : Parent
        {
            public override void Display()
            {
                Console.WriteLine("Child's Method");
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM