C # Polymorphism

Source: Internet
Author: User

1. What is polymorphism?

Another important concept in Object-Oriented Programming is polymorphism. At runtime, you can call methods in the derived class by pointing to the base class pointer. Put a group of objects in an array and call their methods. In this case, polymorphism is manifested. These objects do not have to be of the same type. Of course, if they all inherit from a class, you can put these derived classes into an array. If these objects have methods of the same name, you can call the methods of the same name for each object.

The same operation acts on different objects and can have different interpretations to produce different execution results. This is polymorphism. Polymorphism is implemented by using a derived class to overload the virtual function type method in the base class.

In an object-oriented system, polymorphism is a very important concept. It allows the customer to operate on an object and the object performs a series of actions, the system is responsible for explaining the specific action and implementation.

The word "polymorphism" was first used in biology, which indicates that organisms of the same race possess the same characteristics. In C #, polymorphism is defined as: the same operation acts on instances of different classes. Different classes are interpreted differently and different execution results are generated. C # supports two types of polymorphism:

● Polymorphism during compilation

Polymorphism during compilation is implemented through overloading. For non-Virtual members, during compilation, the system determines the operation based on the passed parameters, returned types, and other information.

● Runtime polymorphism

The running polymorphism is the operation that is performed only when the system is running.In C #, The Runtime polymorphism is implemented by virtual members..

The polymorphism during compilation provides us with a fast running speed, while the polymorphism during runtime brings us a high degree of flexibility and abstraction.

II. Implementation of Polymorphism

Polymorphism is the ability of classes to provide different implementation methods for methods (called with the same name. Polymorphism allows you to call a method of a class without considering the specific implementation provided by the method. For example, a class named road calls the drive method of another class. This other type of car may be sportscar or smallcar, but both provide the drive method. Although the implementation of the drive method varies by class, the road class can still call it, and the results provided by it can be used and interpreted by the road class.

Polymorphism in components can be implemented in different ways:

● Interface polymorphism.

● Inheritance polymorphism.

● Polymorphism implemented through abstract classes.

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, together with the parameter types that each member needs to receive and return, but leave the specific implementations of these Members 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 components 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. Strengths include:

1. 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.

2. Simplified compatibility maintenance, because the new version of the component can continue to provide existing interfaces while adding new interfaces. Later versions of client applications can leverage the strengths of these interfaces.

Polymorphism implemented through inheritance

Multiple classes can be "inherited" from a single base class ". Through inheritance, the class receives any 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 R & D tasks, this is a powerful mechanism, but for large-scale systems, it is often confirmed that there are problems. Over-emphasizing inheritance-driven polymorphism generally results in large-scale transfer of resources from coding to design, which does not help shorten the overall R & D time.

When will the inheritance-driven polymorphism be used? Inheritance is first used to add functions to existing base classes. If you start from the base class framework that has been fully debugged, the efficiency of the programmer will be greatly improved, and the method can be incrementally added to the base class without interrupting the version. When an application is designed to contain multiple related classes, and for some common functions, these related classes must share the same implementation, you may also want to use inheritance. The overlapping function can be implemented in the base class, and the classes used in the application can be derived from the base class. Abstract classes merge inheritance and implementation functions, which may be useful when one of the two elements is required.

Polymorphism implemented through abstract classes

Abstract classes provide inheritance and interface elements at the same time. The abstract class itself cannot be instantiated and must be inherited. Some or all members of this class may not be implemented. This implementation is provided by the inherited class. The implemented members can still be overwritten, And the inherited class can still implement additional interfaces or other functions.

Abstract classes provide inheritance and interface implementation functions. Abstract classes cannot be instantiated and must be implemented in the inheritance class. It can contain implemented methods and attributes, but can also contain unimplemented processes, which must be implemented in the inheritance class. This allows you to provide constant-level functionality in some methods of the class, while enabling options for other processes with flexibility. Another benefit of an abstract class is that when you need a new version of the component, you can add the additional method to the base class as needed, but the interface must remain unchanged.

When to use abstract classes? An abstract class can be used when a group of related components are required to contain a group of methods with the same functions, but at the same time, they must be flexible in other method implementations. Abstract classes are also valuable when version issues are expected, because the base classes are flexible and easy to modify.

Ii. Method coverage and Polymorphism

C # example:
// Myclass. CS

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace myclass
{
Class myfirst
{
Int value_myfirst;
Public myfirst (int f)
{
Value_myfirst = F;
}
Public void F1 ()
{
System. Console. writeline ("myfirst. F1 ()! ");
}
Public Virtual void F2 () // virtual can also be mentioned above
{
System. Console. writeline ("myfirst. F2 ()! ");
}
}

Class mysecond: myfirst
{
Int value_mysecond;

Public mysecond (int s)
: Base (s)
{
Value_mysecond = s;
}

// Use the keyword new to overwrite the method of the same name in the base class
Public new void F1 () // new can also be mentioned above
{
System. Console. writeline ("myseconde. F1 ()! ");
}

// Error when the base class function myfirst. F1 () is not declared as virtual, abstract cannot override!
// Public override void F1 ()
//{
// System. Console. writeline ("myseconde. F1 ()! ");
//}

// Although the declaration of the base class function is virtual, it can still be overwritten with new.
// Public new void F2 ()
//{
// System. Console. writeline ("myseconde. F2 ()! ");
//}

//// The declaration in the base class function is virtual and must be overwritten.
Public override void F2 () // override can also be mentioned above
{
System. Console. writeline ("myseconde. F2 ()! ");
}
}

Class Program
{
Static void main (string [] ARGs)
{
Myfirst mf = new myfirst (1 );
Mysecond MS = new mysecond (2 );
Mf. F1 (); // myfirst. F1 ()!
Mf. F2 (); // myfirst. F2 ()!
Ms. F1 (); // myseconde. F1 ()!
Ms. F2 (); // myseconde. F2 ()!

Mf = MS; // After the upward Transformation
Mf. F1 (); // myfirst. F1 ()!
Mf. F2 (); // myseconde. F2 ()! This is the result of override;
// If it is new, the result is myfirst. F2 ()!

}
}
}

 

Iii. abstract classes

C # example
As mentioned above, although the base class method is declared as virtual, so that the derived class can be overwritten
New Keyword overwrite (no polymorphism ).
You can force a derived class to overwrite the method of the base class, declare the base class method as abstract, and use the abstract keyword.
The abstract method does not have a method body, which is provided by a derived class.

If the derived class does not implement the abstract method of the base class, the derived class must also be declared as the abstract class.

// Myclass. CS

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace myclass {

// As long as there is an abstract method in the class, it must be declared as an abstract class.
Abstract class myfirst
{
Int value_myfirst;
Public myfirst (int f)
{
Value_myfirst = F;
}

// The abstract method does not have a method body, ending with a semicolon.
Public abstract void F1 ();

Public void F2 ()
{
System. Console. writeline ("myfirst. F2 ()! ");
}

Public Virtual void F3 ()
{
System. Console. writeline ("myfirst. F3 ()! ");
}
}

Class mysecond: myfirst
{
Int value_mysecond;

Public mysecond (int s)
: Base (s)
{
Value_mysecond = s;
}

// Override the base class abstract Method
Public override void F1 ()
{
System. Console. writeline ("myseconde. F1 ()! ");
}

// Override the general method of the base class
Public new void F2 ()
{
System. Console. writeline ("myseconde. F2 ()! ");
}

// Override the basic virtual Method
Public override void F3 ()
{
System. Console. writeline ("mysecond. F3 ()! ");
}
}

Class Program
{
Static void main (string [] ARGs)
{
// The abstract class and interface cannot declare an object
// Myfirst mf = new myfirst (1 );
Mysecond MS = new mysecond (2 );

Ms. F1 (); // myseconde. F1 ()!
Ms. F2 (); // myseconde. F2 ()!
Ms. F3 (); // mysecond. F3 ()!

// HereStrong type conversion is adopted for upward TransformationMethod
(Myfirst) MS). F1 (); // myseconde. F1 ()!
(Myfirst) MS). F2 (); // myfirst. F2 ()!
(Myfirst) MS). F3 (); // mysecond. F3 ()!

}
}
}

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.