[Original] inheritance, rewriting, coverage, polymorphism, virtual override and others in C #

Source: Internet
Author: User
Document directory
  • Reference: C # Essence
  • Execution result
  • Result Analysis:
  • Note:
  • Polymorphism and abstract keywords
  • Interface and Polymorphism
Reference: C # Essence

 

Example:
    
using System;using System.Collections.Generic;using System.Linq;using System.Text;    public class BaseClass    {        public virtual void displayName()        {            Console.WriteLine("BaseClass");        }    }    public class DerivedClass : BaseClass    {        public virtual void displayName()        {            Console.WriteLine("DerivedClass");        }         }    public class SubDerivedClass:DerivedClass    {        public override void displayName()        {            Console.WriteLine("SubDerivedClass");        }       }    public class SuperDerivedClass:SubDerivedClass    {        public void displayName()        {            Console.WriteLine("SuperDerivedClass");        }         }    class Program    {        static void Main(string[] args)        {            SuperDerivedClass superDerivedClass = new SuperDerivedClass();            SubDerivedClass subDerivedClass = superDerivedClass;            DerivedClass derivedClass = superDerivedClass;            BaseClass baseClass = superDerivedClass;            superDerivedClass.displayName();            subDerivedClass.displayName();            derivedClass.displayName();            baseClass.displayName();        }    }
Execution result

Result Analysis:

Superderivedclass. displayname ();

 

No need to explain. No subclass, so no polymorphism.

Subderivedclass. displayname ();

Subderivedclass overrides the derivedclass method, and displayname in subderivedclass is also a virtual method. Therefore, when running, try to find the farthest virtual method derived from the inheritance chain, and find that its subclass superderivedclass does not use override, this means that superderivedclass only overwrites the displayname method and does not overwrite it. Therefore, the displayname of the superderivedclass is not executed, but the displayname of the subderivedclass is executed.

 

Derivedclass. displayname ();

Derivedclass overwrites (overwrites, not overwrites, because there is no override label) The baseclass method, but the overwrites method is declared as virtual, therefore, when running, we should try to find the farthest virtual method derived from the inheritance chain and find that its subderivedclass sub-class overwrites this method. So we can continue to find the subderivedclass and find the superderivedclass, it is found that superderivedclass overwrites this method and is not overwritten. Therefore, the subderivedclass displayname method is finally executed.

 

Baseclass. displayname ();

Displayname is a virtual method in baseclass, so it tries to find the farthest derived virtual method. But when we find derivedclass, we find that derivedclass overwrites displayname, and this virtual link is broken. Therefore, you can directly execute the baseclass method.

 

Note:

If the override of subderivedclass is removed, it is not possible to Write Public override void displayname () in superderivedclass. Although there is a virtual displayname in derivedclass for the subclass override, The derivedclass in subderivedclass does not include override, which is equivalent to subderivedclass covering the displayname method of derivedclass, rather than override, the displayname seen in superderivedclass is actually the dislayname of subderivedclass. It is a non-virtual method instead of a virtual method inherited from derivedclass.

Summary

If a class has one method, the method is a virtual method only in two cases.

1: This method is defined by virtual.

2: There is a virtual method with the same name in the parent class of this class. In this class, the override keyword is used to override the virtual method of the parent class.

To "Override" a subclass rather than "Overwrite" A parent class, two conditions must be met.

1. "The parent method is a virtual method. (This means that this method is either marked as virtual, or override its parent class .)".

2. "The subclass has the override mark ".

If either of them is missing, it means that the subclass overwrites the method of the parent class, rather than overwrites the method ".

If a method is a virtual method (), it is executed by looking for the "Override" method in the runtime. Once "Overwrite" is encountered, the inheritance chain is broken.

 

Added content polymorphism and abstract keywords in June 23

The abstract method is a virtual method by default, and the subclass must be explicitly rewritten using the override keyword. The override method in the subclass is also a virtual method by default, which can be rewritten by other classes.

Example

Using system; public abstract class father {public abstract void dowork ();} public class child: Father {public override void dowork () // This method is a virtual method, can be rewritten by subclass {console. writeline ("this is child") ;}} public class grandchild: child {public override void dowork () // This method is a virtual method and can be rewritten by the subclass {console. writeline ("this is grandchild ~ ") ;}} Public class m {public static void main () {father f = new grandchild (); F. dowork ();}}

Because of the polymorphism mechanism, the running result is "This is grandchild ~"

Interface and Polymorphism

Interface-related polymorphism is not suitable for the above analysis method. The above analysis is only effective for polymorphism between pure classes.

The methods in the interface are compiled as virtual by default, and the methods implemented in the interface implementation class are also compiled as override by default. However, the methods implemented in the interface implementation class cannot use the override keyword explicitly, nor automatically become virtual methods like the override method in the class. To make this method virtual, virtual must be explicitly added.

Example:

using System;public class Father : MyInterface{    public void doWork()    {        Console.WriteLine("Father");    }}public interface MyInterface{    void doWork();}public class Child : Father{    public void doWork()    {        Console.WriteLine("Child");    }}public class M{    public static void Main()    {        MyInterface f = new Child();        f.doWork();    }}

The running result is "Father ".

Analysis:

When a function is called as an interface, Father. dowork () is called, indicating that the polymorphism mechanism has taken effect. But because of Father. dowork () is not a virtual method by default. Therefore, child cannot override this method and can only overwrite father. the dowork () method tries. the override keyword added before dowork () cannot be compiled.

If father. add the virtual keyword before dowork () and. when the override keyword is added before dowork (), the running result is changed to child, indicating that the virtual chain issued from the interface can be extended infinitely, rather than the class that implements the interface.

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.