In layman's OOP (c): Polymorphism and Inheritance (Dynamic binding/runtime Polymorphism)

Source: Internet
Author: User

In the previous article, we introduced the compile-time polymorphism, the params keyword, the instantiation, the base keyword, and so on. In this section, we focus on another polymorphic: run-time polymorphic, run-time polymorphic, also called late binding.

Run-time polymorphic or late binding, dynamic binding

In C # speech, run-time polymorphism is also called method rewriting (overriding), we can overriding the same signature function of the base class in the subclass, using the "Virtual & override" keyword.

The new, override keyword for C #

Create a console example project, namedInheritanceAndPolymorphism。在Program.cs基础上,再添加2个类文件,分别命名为ClassA.cs、ClassB.cs。拷贝如下代码:

 Public classClassA { Public voidAAA () {Console.WriteLine ("ClassA AAA"); }         Public voidBBB () {Console.WriteLine ("ClassA BBB"); }         Public voidCCC () {Console.WriteLine ("ClassA CCC"); }    }

ClassB:

 Public classClassB { Public voidAAA () {Console.WriteLine ("ClassB AAA"); }         Public voidBBB () {Console.WriteLine ("ClassB BBB"); }         Public voidCCC () {Console.WriteLine ("ClassB CCC"); }    }

In the above code, we can see that ClassA, CLASSB have the same signature method, can be used directly in the Program.cs .

We'll do the rest of the code, with the following structure:

/// <summary>    ///ClassB, acting as a base class/// </summary>     Public classClassB { Public voidAAA () {Console.WriteLine ("ClassB AAA"); }         Public voidBBB () {Console.WriteLine ("ClassB BBB"); }         Public voidCCC () {Console.WriteLine ("ClassB CCC"); }    }    /// <summary>    ///Class A, acting as a derived class/// </summary>     Public classCLASSA:CLASSB { Public voidAAA () {Console.WriteLine ("ClassA AAA"); }         Public voidBBB () {Console.WriteLine ("ClassA BBB"); }         Public voidCCC () {Console.WriteLine ("ClassA CCC"); }    }

Program.cs

Main (= = =

F5, run the code with the following results:

ClassA AAA

ClassA BBB

ClassA CCC

ClassB AAA

ClassB BBB

ClassB CCC

ClassB AAA

ClassB BBB

ClassB CCC

But at the same time, in the Output window of VS, we got 3 warnings:

' InheritanceAndPolymorphism.ClassA.AAA () ' hides inherited member

' InheritanceAndPolymorphism.ClassB.AAA () '. Use the New keyword if hiding is intended.

' InheritanceAndPolymorphism.ClassA.BBB () ' hides inherited member

' InheritanceAndPolymorphism.ClassB.BBB () '. Use the New keyword if hiding is intended.

' InheritanceAndPolymorphism.ClassA.CCC () ' hides inherited member

' InheritanceAndPolymorphism.ClassB.CCC () '. Use the New keyword if hiding is intended.

The reason for these warnings is because the subclass and the base class AAA, BBB, CCC method signature is the same, although from the implementation of the first implementation of the method of sub-similar signature, but there may be potential problems, so warnings proposed.

Refactoring experiment

Based on the above warning, we manually modified the code to see how to eliminate these warnings.

First, add the new, override keyword to the subclass to try it:

/// <summary>    ///Class A, acting as a derived class/// </summary>     Public classCLASSA:CLASSB { Public Override voidAAA () {Console.WriteLine ("ClassA AAA"); }         Public New voidBBB () {Console.WriteLine ("ClassA BBB"); }         Public voidCCC () {Console.WriteLine ("ClassA CCC"); }    }

The result of the execution is an error:

Error: ' InheritanceAndPolymorphism.ClassA.AAA () ': Cannot override inherited member ' InheritanceAndPolymorphism.ClassB.AAA () ' because it's not marked virtual, abstract, or override

From this error message we need to modify the base class method, such as adding the virtual keyword.

Main (= = =

Execution, then there is no warning, through this example, we know that by adding the virtual keyword in the base class to authorize its subclasses can override the same signature method of the permission to facilitate the expansion of OOP.

Run-time polymorphism of 3 classes

InClassA\ClassB基础上,下面添加ClassC,看看3个类继承关系的运行时多态:

Main (= = =

Operation Result:

ClassB AAA

ClassB BBB

ClassA CCC

ClassB AAA

ClassB BBB

ClassA CCC

ClassC AAA

ClassA BBB

ClassA CCC

If the base class declares thevirtual 关键字,子类可使用override修饰符实现运行时多态:只有在编译器动态决定是否被调用。

如果未标明virtual或非virtual,则方法是否被调用在编译期就能决定。

Take a look at the following example:

Internal classA { Public Virtual voidX () {}}Internal classb:a { Public New voidX () {}}Internal classc:b { Public Override voidX () {}}

F5 operation, the result is error:

Error: ' inheritanceandpolymorphism.c.x () ': Cannot override inherited member ' inheritanceandpolymorphism.b.x () ' Because it is not marked virtual, abstract, or override

The reason for the error is that the X function of virtual is defined in a, and the X function in a is hidden in B with the new keyword. When C tries to pass the override keyword, it is not able to get the virtual keyword x function in a, and the X function in C is not virtual, so it cannot be override.

Cut off the relationship
Main (= =

The results of the implementation are as follows:

class:a; Method Xclass:c; Method X

Here we add the new virtual modifier to Class B, and then we can use the X function of virtual in B in C.

Run-time polymorphism of 4 classes

On the above inheritance, add a fourth class in run-time polymorphism: CLASSD.

Main (= = = =

The results of the implementation are as follows:

ClassB XXX

ClassB XXX

CLASSD XXX

CLASSD XXX

The first line of output, from a. XXX () function, we define the XXX function in ClassA, and then use the New keyword in CLASSB to cut off the virtual relationship-the subclass. Therefore, the XXX function from CLASSC began to become a new virtual function, in this code A is a CLASSD instance, but the declaration of ClassA, so from the bottom of the search, find the ClassB xxx function, print and output results.

A never-ending cycle

Main (=

Operation Error:

Error: {Cannot evaluate expression because the current thread was in a stack overflow state.}

In this example, ((ClassA) this). XXX (); Causes the loop call to be modified to base. XXX can fix the cyclic call caused by this strong turn.

Conclusion
    • In C #, a subclass object can be assigned to a base class object, whereas a strong turn is required.

    • The override keyword is used for subclasses overriding the same signature as the base class virtual function

    • Use new and override to override the same signature function of the base class virtual

    • A function of the virtual modifier that can only be executed at run time

    • function is not modified by virtual, it can be determined at compile time whether it is called

Original link: Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic binding/run time polymorphism)

In layman's OOP (c): Polymorphism and Inheritance (Dynamic binding/runtime Polymorphism)

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.