In-depth analysis of C # polymorphism 3

Source: Internet
Author: User
Overload the virtual method in the derived class

Let's review the normal method overload. The normal method overload refers to two or more methods in the class (including hidden inherited methods) with the same name, as long as the parameter type or number of parameters are different, the compiler knows under which method should be called.

The overload of base-class virtual methods is another special form of function overload. When a new virtual function is defined in a derived class, the method name is required. The return value type, number of parameters in the parameter table, and type sequence must be exactly the same as the virtual function in the base class. To declare an overload of a virtual method in a derived class, you must add the override keyword to the declaration and do not have new, static, or virtual modifiers.

Let's look at an example of using a car to illustrate the implementation of polymorphism.Program:

Using system;

Class vehicle // defines the vehicle class

{

Public int wheels; // Number of public member wheels

Protected float weight; // the weight of the protected member.

Public Vehicle (int w, float g)

{

Wheels = W;

Weight = g;

}

Public Virtual void speak ()

{

Console. writeline ("the W vehicle is speaking! ");

}

};

Class car: Vehicle // defines the car type

{

Int passengers; // number of private member passengers

Public Car (int w, float g, int P): Base (W, g)

{

Wheels = W;

Weight = g;

Passengers = P;

}

Public override void speak ()

{

Console. writeline ("the car is speaking: di-di! ");

}

}

Class truck: Vehicle // define the truck class

{

Int passengers; // number of private member passengers

Float load; // Private member Load

Public truck (int w, float g, int P, float L): Base (W, g)

{

Wheels = W;

Weight = g;

Passengers = P;

Load = L;

}

Public override void speak ()

{

Console. writeline ("the truck is speaking: Ba-Ba! ");

}

Public static void main ()

{

Vehicle V1 = new vehicle (0, 0 );

Car C1 = new car (4,2, 5 );

Truck T1 = new truck (6, 5, 3, 10 );

V1.speak ();

V1 = C1;

V1.speak ();

C1.speak ();

V1 = T1;

V1.speak ();

T1.speak ();

}

}

The above example shows:

● If the Speak method in the vehicle class is declared as a virtual method, you can redefine this method in the derived class.

● The speak method is overloaded in the derived classes car and truck respectively. The method prototype in the derived class must be exactly the same as the method prototype in the base class.

● In the test class, instance V1 of the vehicle class is created and has been directed to instance C1 of the car class and instance T1 of the truck class.

The result of running the program should be:

The vehicle is speaking!

The car is speaking: di-di!

The car is speaking: di-di!

The truck is speaking: Ba-Ba!

The truck is speaking: Ba-Ba!

Here, instance V1 of the vehicle class is successively assigned to instance C1 of the car class and the value of instance T1 of the truck class. During execution, V1 successively refers to instances of different classes and calls different versions. Here, the Speak method of V1 implements polymorphism, and the version of v1.speak is not determined during program compilation, but during Dynamic Running of the program, it is determined based on the reference type of V1 at a certain time point, so it also reflects the dynamic polymorphism.

Iv. Interface Polymorphism

Multiple classes can implement the same "interface", while a single class can implement one or more interfaces. An interface is essentially a definition of how the class needs to respond. The methods, attributes, and events that the interface description class needs to implement, and the parameter types that each member needs to receive and return, but the specific implementations of these members are left to the implementation class for completion.

One powerful technology in component programming is the ability to implement multiple interfaces on an object. Each interface consists of a small number of closely related methods, attributes, and events. Through the implementation interface, the component can provide functions for any other component that requires the interface, without considering the specific functions contained in it. This allows subsequent component versions to include different functions without interfering with core functions.

The component functions most commonly used by other developers are naturally members of the component class. However, components that contain a large number of Members may be difficult to use. Some functions of the component can be considered as separate interfaces implemented in private.

Another benefit of defining features based on interfaces is that you can incrementally add features to components by defining and implementing additional interfaces. Advantages include:

● The design process is simplified because the components can be very small at the beginning and have the minimum function. Later, the components continue to provide the minimum function while inserting other functions, and determine the appropriate functions by actually using those functions.

● The compatibility maintenance is simplified, because the new version of the component can continue to provide existing interfaces while adding new interfaces. Later versions of client applications can take advantage of these interfaces (if this makes sense ).

5. Inheritance Polymorphism

Multiple classes can be "inherited" from a single base class ". Through inheritance, the class receives all methods, attributes, and events of the base class in the same Implementation of the base class. In this way, you can add members as needed, and rewrite the base members to provide different implementations. Note that inheritance classes can also implement interfaces. These two technologies are not mutually exclusive.

C # provide polymorphism through inheritance. For small-scale development tasks, this is a powerful mechanism, but for large-scale systems, it is often proved that there are problems. Over-emphasizing inheritance-driven polymorphism generally results in the large-scale transfer of resources from coding to design, which does not help shorten the overall development time. See the following example:

Class B

{Public Virtual void Foo (){}}

Class D: B

{

Public override void Foo (){}

}

// An attempt to reload a non-virtual method will result in a compilation error, unless the "new" keyword is added to the method, // to indicate the method to hide the parent class.

Class N: d

{

Public new void Foo (){}

Public static void main (){

N = new N ();

N. Foo (); // call n's foo

(D) N). Foo (); // call Foo of d

(B) N). Foo (); // call Foo of d

}

}

Compared with C ++ and Java, the override keyword of C # enables readingSource codeYou can clearly see which methods are overloaded. However, the use of virtual methods has advantages and disadvantages. The first advantage is to avoid using virtual methods to slightly increase the execution speed. The second point is to clearly know which methods will be overloaded.

Let's look at a class about aircraft description. Suppose we have a base class that describes airplanes. Now, we need to complete an aircraft control system with a global function fly, which is responsible for sending the plane to take off. Then, we only need to do this:

Using system;

Class plane

{

Public Virtual void fly () {}// retrieves pure virtual functions

Public Virtual void land () {}// landing pure virtual function

Public Virtual string modal () {}// search for model pure virtual functions

}

// Then, we derive two sub-classes from plane: copter and jet ):

Class copter: Plane

{

Private string fmodal;

Public override void fly (){}

Public override void land (){}

Public override string modal (){}

}

Class jet: Plane

{

Private string fmodal;

Public override void fly (){}

Public override void land (){}

Public override string modal {}

}

This allows all planes that pass on to it (child objects of plane) to take off normally! Whether it's a helicopter, a jet, or even a flying saucer that doesn't exist now, it will be added in the future. Because each subclass has defined its own departure method.

We can see plane. the fly () function accepts the plane Class Object Reference of the parameter, and all the objects actually passed to it are the Child class objects of plane, polymorphism is a technique that allows you to set a parent object to be equal to one or more of its sub-objects, the parent object can operate in different ways based on the features of the sub-objects assigned to it. Apparently, parent = Child; is the essence of polymorphism! Because a helicopter is a plane and a jet is a plane, all operations on the plane can be performed on them. At this time, aircraft is used as an interface. The essence of polymorphism is to assign the pointer of the subclass type to the pointer of the parent class (referenced in OP). As long as such a value is assigned, polymorphism is generated, because "upward ing" is implemented ".

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.