Polymorphism in C #

Source: Internet
Author: User

Polymorphism

First understand what polymorphism is. The same action acts on different objects, can have different interpretations, and produces different execution results, which is polymorphism.

Polymorphism is implemented by using a derived class to override the virtual function type method in the base class.

There are two kinds of polymorphism, one is polymorphism at compile time and one is polymorphism of runtime.

Compile-time polymorphism: Compile-time polymorphism is implemented by overloading. For non-virtual members, the system compiles, depending on the parameters passed, the type of return, and other information to decide what to do.

Runtime polymorphism: Runtime polymorphism means that the operation is not determined according to the actual situation until the system is running. The runtime polymorphism in C # is achieved by covering virtual members.

Let's take a look at the four concepts involved in polymorphism: overloading, overriding, virtual methods, and abstract methods.

The difference between overloading and overriding:

Overload

Different versions of methods defined in a class

public int Calculate (int x, int y)

Public double Calculate (double x, double y)

Features (two must be one can)

Method names must be the same

Parameter list must be different

Return value types can be different

Overwrite

subclasses define different implementations of a method in order to meet their own needs.

Overwrite is achieved by using the Override keyword.

Only virtual methods and abstract methods can be overwritten.

Requirements (three same)

The same method name

The same argument list

The same return value type

Cases:

public class Test

{

public int Calculate (int x, int y)

{

return x + y;

}

Public double Calculate (double x, double y)

{

return x + y;

}

}

First look at this class, we meet the overload in the same class three characteristics, the method name must be the same calculate; The argument list must be different for the first method, the two parameter type is int, and the second method has two parameter types of type double The return value type can be different, one return value type is int, and the other return value type is double.

Then we call these two methods in the client program.

At this point, we find that the smart tip indicates that this method has been overloaded once. This allows us to invoke different methods based on the business logic to achieve different business.


Client test Program:

Test T = new Test ();

int x;

int y;

Console.WriteLine ("Please input an integer.\n");

x = Convert.ToInt32 (Console.ReadLine ());

Console.WriteLine ("Please input another integer.\n");

y = Convert.ToInt32 (Console.ReadLine ());

Console.WriteLine ("Test class Calculate method result.\n");

int RESULT1 = t.calculate (x, y);

Console.WriteLine ("int x + int y = {0}\n", result1. ToString ());

Double A;

Double b;

Console.WriteLine ("Please input an double.\n");

A = Convert.todouble (Console.ReadLine ());

Console.WriteLine ("Please input another double.\n");

b = convert.todouble (Console.ReadLine ());

Console.WriteLine ("Test class Calculate method result.\n");

Double result2 = T.calculate (A, b);

Console.WriteLine ("Double x + double y = {0}\n", result2. ToString ());

Console.ReadLine ();

The result of the execution is:

Let's take a look at the overwrite, we'll change the base class (parent Class)

public class Test

{

public virtual int Calculate (int x, int y)

{

return x + y;

}

Public virtual double Calculate (double x, double y)

{

return x + y;

}

}

Derived classes (child classes)

public class Testoverride:test

{

public override int Calculate (int x, int y)

{

return x * y;

}

public override double Calculate (double x, double y)

{

return x * y;

}

}

This is what we will find in the client testing program, we can access to the Overwrite method can also access to overwrite the previous method of the base class, display is overloaded 3 times, of which two times is overwritten





Client test Program

Testoverride t = new testoverride ();

int x;

int y;

Console.WriteLine ("Please input an integer.\n");

x = Convert.ToInt32 (Console.ReadLine ());

Console.WriteLine ("Please input another integer.\n");

y = Convert.ToInt32 (Console.ReadLine ());

Console.WriteLine ("Test class Calculate method result.\n");

int RESULT1 = t.calculate (x, y);

Console.WriteLine ("int x * int y = {0}\n", result1. ToString ());

Double A;

Double b;

Console.WriteLine ("Please input an double.\n");

A = Convert.todouble (Console.ReadLine ());

Console.WriteLine ("Please input another double.\n");

b = convert.todouble (Console.ReadLine ());

Console.WriteLine ("Test class Calculate method result.\n");

Double result2 = T.calculate (A, b);

Console.WriteLine ("Double x * Double y = {0}\n", result2. ToString ());

Console.ReadLine ();

The result of the execution is:

Here's another thing to mention is that in subclasses, if you need access to the parent class, you can use the base keyword, for example:

public class Testoverride:test

{

public override int Calculate (int x, int y)

{

Return base. Calculate (x, y);

}

public override double Calculate (double x, double y)

{

Return base. Calculate (x, y);

}

}

This allows us to return the result of the addition operation when the client program accesses the method that inherits the test class Testoverride class.

Let's take a comparison of the overloaded and covered writing

Override Overwrite

Overload overloaded

Position

In a class that exists in an inheritance relationship

exist in the same class

Method name

Same

Same

Parameter list

Same

Must be different

return value

Same

can be different

Finally, we introduce the virtual method and the abstract method.

Virtual method

The declaration uses the virtual keyword.

Calling a virtual method, the runtime determines the instance of what class the calling object is, and invokes the appropriate override method.

Virtual methods can have an implementation body.

Abstract methods

Methods that must be overridden by a derived class.

Can be seen as a virtual method without implementing the body.

If the class contains an abstract method, the class must be defined as an abstract class, whether or not it contains other general methods.

We've done some experiments on virtual methods, and here's an example of an abstract approach.

Cases:

public class Testoverride:test

{

public abstract int Calculate (int x, int y);

public abstract double Calculate (double x, double y);

}

An error will occur at compile time.

Requires that the abstract method must be printed in the abstract class, we make the following changes

Public abstract class Testoverride:test

{

public abstract int Calculate (int x, int y);

public abstract double Calculate (double x, double y);

}

This satisfies the requirements of the abstract method and can be compiled by

We can also overwrite it, in fact, the overwrite is what we call an abstract concrete implementation. As shown in the above ion, we first define a test class with an abstract class and define it in which the class can do two integer or real number calculation operations, as to what kind of calculation and how the calculation is not defined, just declare I can do these things, and then in its subclasses (a specific class) to implement his definition, What we're going to do is multiply the calculations. We can also define by another specific class that what we may want to do is not multiplication but addition. The code is as follows:

public class Testadd:test

{

public override int Calculate (int x, int y)

{

return x + y;

}

public override double Calculate (double x, double y)

{

return x + y;

}

}

This allows us to use abstract classes to define operations, and to use specific classes to implement different operations depending on the situation. This leads to the factory methods, builders, abstract factory methods in the pattern of creation in our design pattern (these are the patterns I've learned for the time being), and if you want to understand this knowledge you can refer to the Terrylee Design pattern series, which is classic.

So far, we have introduced several concepts of polymorphism in C #, and hope that we can help you in the future Code structure design:)

There are a few complaints here that the changes in the current project are very common, and the software we are designing is to adapt to this constant change, to encapsulate some of the change points in the project, and to respond easily to changes in our business. A software is bound to go through the parts of its life cycle and finally to death, but we can in the design by enabling the software to respond to these changes to make it longer life, will bring us more value (haha, these are actually the design pattern to achieve some of the purpose).

Hope you can get some gains from this article, thank you:)

Polymorphism in C #

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.