C # Implementation of polymorphism,

Source: Internet
Author: User

C # Implementation of polymorphism,

The first two features of encapsulation, inheritance, polymorphism, and object-oriented are relatively easy to understand, but understanding polymorphism, especially in-depth understanding, may be difficult for beginners. I always think that the best way to learn OO is to combine practice, encapsulate and inherit the application in actual work, which can be seen everywhere, but what about polymorphism? It may not be necessary. It may be used inadvertently and will not correspond to the word "polymorphism. I would like to discuss with you that your personal abilities are limited. please correct me if you have any shortcomings.
I have seen a similar question before: What would you do if the examiner asked you to describe polymorphism in one sentence and refine it as much as possible? Of course, there are many answers. Each person has different understandings and expressions, but I tend to describe this: different objects implemented by inheritance call the same method and show different behaviors, called polymorphism.

Example 1:

Code
public class Animal    {        public virtual void Eat()        {            Console.WriteLine("Animal eat");        }    }    public class Cat : Animal    {        public override void Eat()        {            Console.WriteLine("Cat eat");        }    }    public class Dog : Animal    {        public override void Eat()        {            Console.WriteLine("Dog eat");        }    }    class Tester    {        static void Main(string[] args)        {            Animal[] animals = new Animal[3];            animals[0] = new Animal();            animals[1] = new Cat();            animals[2] = new Dog();            for (int i = 0; i < 3; i++)            {                animals[i].Eat();            }        }    }

The output is as follows:

Animal eat...

Cat eat...

Dog eat...

In the above example, different objects in the Animal object array are inherited, and different behaviors are displayed when the Eat () method is called.

The implementation of polymorphism seems very simple. It is not easy to fully understand and flexibly use the c # polymorphism mechanism. There are many things to pay attention.

 

1. Usage of new

Let's take a look at the example below.

Example 2:

 

Code
public class Animal    {        public virtual void Eat()        {            Console.WriteLine("Animal eat");        }    }    public class Cat : Animal    {        public new void Eat()        {            Console.WriteLine("Cat eat");        }    }    class Tester    {        static void Main(string[] args)        {            Animal a = new Animal();            a.Eat();            Animal ac = new Cat();            ac.Eat();            Cat c = new Cat();            c.Eat();        }    }

The running result is:

Animal eat...

Animal eat...

Cat eat...

It can be seen that when the Cat Eat () method of the derived class is modified with new, the Cat object is converted to an Animal object, and the Eat () method in the Animal class is called. It can be understood that, after the new keyword is used, the Eat () method in Cat and the Eat () method in Animal become irrelevant, but their names happen to be the same. Therefore, no matter whether the Eat () method in the Animal class is used or virtual modification is not required, or whether the access permission is the same or not, the Eat () method of Cat () impact of the method (only because the new keyword is used, if the Cat class does not inherit the Eat () method from the Animal class, the compiler will output a warning ).

 

I think it was designed by the designer, because sometimes we want to achieve this effect. Strictly speaking, we can't say that we use new to achieve polymorphism. We can only say that we happen to achieve polymorphism at some specific times.

 

 

2. override Implementation of Polymorphism

True polymorphism is implemented using override. Go back to the previous example 1, mark the method Eat () as a virtual method in the base class Animal, and then modify the Eat () with override in the Cat and Dog classes to rewrite it, it is easy to implement polymorphism. Note that override must be used to modify a method in a class. The class must inherit a virtual method modified by virtual from the parent class. Otherwise, the compiler reports an error.

 

It seems like you have talked about it. There is another problem. I don't know if you want. It is how multi-layer inheritance achieves polymorphism. For example, Class A is A base class and has A virtual method () (virtual modifier). Class B inherits from Class A and override the method ), now class C inherits from Class B. Can I continue to rewrite method () and implement polymorphism? Let's look at the example below.

 

Example 3:

 

Code
public class Animal    {        public virtual void Eat()        {            Console.WriteLine("Animal eat");        }    }    public class Dog : Animal    {        public override void Eat()        {            Console.WriteLine("Dog eat");        }    }    public class WolfDog : Dog    {        public override void Eat()        {            Console.WriteLine("WolfDog eat");        }    }    class Tester    {        static void Main(string[] args)        {            Animal[] animals = new Animal[3];            animals[0] = new Animal();            animals[1] = new Dog();            animals[2] = new WolfDog();            for (int i = 0; i < 3; i++)            {                animals[i].Eat();            }        }}

The running result is:

Animal eat...

Dog eat...

WolfDog eat...

In the above example, class Dog inherits from class Animal and overwrites the method Eat (), Class WolfDog inherits from Dog, and the Eat () method is rewritten again, polymorphism is also achieved. No matter how many layers are inherited, you can rewrite the methods that have been overwritten in the parent class in the subclass. That is, if the parent class method is modified with override, if the subclass inherits the method, you can also use override to modify the multi-layer inheritance. To terminate this rewrite, you only need to modify the method with the sealed keyword.

 

 

3. abstract-override Implementation of Polymorphism

Let's first discuss the abstract method with abstract modification. Abstract methods are defined but not implemented. If a class contains abstract methods, the class must also be declared as an abstract class. An abstract class cannot be instantiated. For abstract methods in a class, override can be used in its derived class to overwrite them. If they are not overwritten, Their Derived classes will also be declared as abstract classes. Let's look at the example below.

Example 4:

 

 

Code
public abstract class Animal    {      public abstract void Eat();    }    public class Cat : Animal    {        public override void Eat()        {            Console.WriteLine("Cat eat");        }    }    public class Dog : Animal    {        public override void Eat()        {            Console.WriteLine("Dog eat");        }    }    public class WolfDog : Dog    {        public override void Eat()        {            Console.WriteLine("Wolfdog eat");        }    }    class Tester    {        static void Main(string[] args)        {            Animal[] animals = new Animal[3];            animals[0] = new Cat();            animals[1] = new Dog();            animals[2] = new WolfDog();            for (int i = 0; i < animals.Length; i++)            {                animals[i].Eat();            }        }    }

The running result is:

Cat eat...

Dog eat...

Wolfdog eat...

As can be seen from the above, abstract-override can be used to achieve polymorphism like virtual-override, including multi-layer inheritance. The difference is that classes containing virtual methods can be instantiated, while classes containing abstract methods cannot be instantiated.

The above motion graphs are provided by "Graph dado ".

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.