Polymorphism (C # programming guide)

Source: Internet
Author: User

Visual Studio 2010
 
Other Versions

Visual Studio 2008
Visual Studio 2005
 
 
Polymorphism is often seen as the third pillar of object-oriented programming after self-sealing and inheritance. Polymorphism (Polymorphism) is a Greek term that refers to "multiple forms". Polymorphism has two distinct aspects:
During runtime, the objects of the derived class can be processed as the objects of the base class at the location of the method parameter, set, or array. In this case, the object declaration type is no longer the same as the runtime type.
The base class can define and implement virtual methods. The derived class can override these methods, that is, the derived class provides its own definition and implementation. When running, the client code calls this method. CLR searches for the runtime type of the object and calls the virtual method override method. Therefore, you can call the base class method in the source code, but execute the derived class version of this method.
The virtual method allows you to process multiple groups of related objects in a unified manner. For example, assume that you have a drawing application that allows you to create various shapes on the drawing. You do not know which types of shapes will be created during compilation. However, the application must track all types of shapes created and update these shapes in response to user mouse operations. You can use polymorphism to solve this problem through two basic steps:
Create a class hierarchy. Each specific shape class is derived from a common base class.
Use the virtual method to call the corresponding methods on any derived class by calling a single base class method.
First, create a base class named Shape and create some Derived classes, such as Rectangle, Circle, and Triangle. A virtual method named Draw is provided for the Shape class, and this method is rewritten in each derived class to Draw a specific Shape represented by this class. Create a List <Shape> object and add Circle, Triangle, and Rectangle to the object. To update a drawing, use the foreach loop to cyclically access the list and call the Draw method for each Shape object. Although each object in the list has a declared type Shape, it calls a runtime type (this method is rewritten in each derived class ).


 
VB
C #
C ++
F #
JScript

Copy
Public class Shape
{
// A few example members
Public int X {get; private set ;}
Public int Y {get; private set ;}
Public int Height {get; set ;}
Public int Width {get; set ;}

// Virtual method
Public virtual void Draw ()
{
Console. WriteLine ("Deming base class drawing tasks ");
}
}

Class Circle: Shape
{
Public override void Draw ()
{
// Code to draw a circle...
Console. WriteLine ("Drawing a circle ");
Base. Draw ();
}
}
Class Rectangle: Shape
{
Public override void Draw ()
{
// Code to draw a rectangle...
Console. WriteLine ("Drawing a rectangle ");
Base. Draw ();
}
}
Class Triangle: Shape
{
Public override void Draw ()
{
// Code to draw a triangle...
Console. WriteLine ("Drawing a triangle ");
Base. Draw ();
}
}

Class Program
{
Static void Main (string [] args)
{
// Polymorphism at work #1: a Rectangle, Triangle and Circle
// Can all be used whereever a Shape is expected. No cast is
// Required because an implicit conversion exists from a derived
// Class to its base class.
System. Collections. Generic. List <Shape> shapes = new System. Collections. Generic. List <Shape> ();
Shapes. Add (new Rectangle ());
Shapes. Add (new Triangle ());
Shapes. Add (new Circle ());

// Polymorphism at work #2: the virtual method Draw is
// Invoked on each of the derived classes, not the base class.
Foreach (Shape s in shapes)
{
S. Draw ();
}

// Keep the console open in debug mode.
Console. WriteLine ("Press any key to exit .");
Console. ReadKey ();
}

}

/* Output:
Drawing a rectangle
Ming base class drawing tasks
Drawing a triangle
Ming base class drawing tasks
Drawing a circle
Ming base class drawing tasks
*/


In C #, each type is polymorphism, because all types including user-defined types inherit from objects.
Summary of Polymorphism
Virtual Member
When a derived class inherits from a base class, it obtains all methods, fields, attributes, and events of the base class. The designer of the derived class can choose whether
Override virtual members in the base class.
Inherits the closest base class method without rewriting it.
Defines new non-virtual implementations of hidden base class implementation members
Only when the base class member is declared as virtual or abstract can the derived class override the base class member. The derived member must use the override keyword to explicitly indicate that this method will be used for virtual calls. The following code provides an example:


 
VB
C #
C ++
F #
JScript

Copy
Public class BaseClass
{
Public virtual void DoWork (){}
Public virtual int WorkProperty
{
Get {return 0 ;}
}
}
Public class DerivedClass: BaseClass
{
Public override void DoWork (){}
Public override int WorkProperty
{
Get {return 0 ;}
}
}


Fields cannot be virtual. Only methods, attributes, events, and indexes can be virtual. When a derived class overrides a virtual member, the Member is called even if the instance of the derived class is accessed as a base class instance. The following code provides an example:


 
VB
C #
C ++
F #
JScript

Copy
DerivedClass B = new DerivedClass ();
B. DoWork (); // callthe new method.

BaseClass A = (BaseClass) B;
A. DoWork (); // Also callthe new method.


Virtual Methods and attributes allow the derived class to expand the base class, without the need to use the base class implementation of the method. For more information, see use the Override and New keywords for version control (C # programming guide ). The interface provides another way to define the methods or method set that will be left to the derived class. For more information, see the interface (C # Programming Guide) and select between classes and interfaces.
Hide base class members with new members
If you want the derived member to have the same name as the member in the base class, but do not want the derived member to participate in the virtual call, you can use the new keyword. The new keyword is placed before the return type of the class member to be replaced. The following code provides an example:


 
VB
C #
C ++
F #
JScript

Copy
Public class BaseClass
{
Public void DoWork () {WorkField ++ ;}
Public int WorkField;
Public int WorkProperty
{
Get {return 0 ;}
}
}

Public class DerivedClass: BaseClass
{
Public new void DoWork () {WorkField ++ ;}
Public new int WorkField;
Public new int WorkProperty
{
Get {return 0 ;}
}
}


By forcibly converting the instance of the derived class to the base class instance, you can still access the hidden base class members from the client code. For example:


 
VB
C #
C ++
F #
JScript

Copy
DerivedClass B = new DerivedClass ();
B. DoWork (); // callthe new method.

BaseClass A = (BaseClass) B;
A. DoWork (); // callthe old method.


Prevents a derived class from overwriting a virtual member.
No matter how many classes have been declared between the virtual member and the class that originally declares the Virtual Member, the virtual member is always virtual. If Class A declares A virtual Member, Class B is derived from Class A and Class C is derived from Class B, Class C inherits the Virtual Member and can choose to override it, regardless of whether Class B declares a rewrite for this member. The following code provides an example:


 
VB
C #
C ++
F #
JScript

Copy
Public class
{
Public virtual void DoWork (){}
}
Public class B:
{
Public override void DoWork (){}
}


A derived class can stop virtual inheritance by declaring the override as sealed. This requires the sealed keyword before the override keyword in the class member declaration. The following code provides an example:


 
VB
C #
C ++
F #
JScript

Copy
Public class C: B
{
Public sealed override void DoWork (){}
}


In the previous example, the method DoWork is no longer a virtual method for any class derived from C. Even if they are converted to type B or type A, it is still virtual for instances of type C. By using the new keyword, the sealing method can be replaced by the derived class, as shown in the following example:


 
VB
C #
C ++
F #
JScript

Copy
Public class D: C
{
Public new void DoWork (){}
}


In this case, if you use a variable of the D type in D to call DoWork, the new DoWork will be called. If A variable of type C, B, or A is used to access the instance of D, the call to DoWork follows the rules of virtual inheritance, that is, these calls are transmitted to the DoWork Implementation of class C.
Access virtual members of the base class from a derived class
A derived class that has replaced or overwritten a method or attribute can still use the base keyword to access this method or attribute of the base class. The following code provides an example:


 
VB
C #
C ++
F #
JScript

Copy
Public class Base
{
Public virtual void DoWork (){/*...*/}
}
Public class Derived: Base
{
Public override void DoWork ()
{
// Perform Derived's work here
//...
// Call DoWork on base class
Base. DoWork ();
}
}

Author: "Computer Encyclopedia (only used for technology .."

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.