Polymorphism in C #

The word polymorphism means that there are many forms. In object-oriented programming, polymorphism is often expressed as "one Interface, multiple functions".

Polymorphism in C # can be static or dynamic . In particular, a static polymorph can be called a static polymorph, a response to a function defined at compile time and a dynamic polymorph can be called dynamic polymorphism, defined at runtime .

Static polymorphism in C #

The technique of linking a function to an object during compilation is called Early Binding. It is also called Static Binding. C # provides two techniques for deploying static polymorphisms, namely:

  1. Load overlap (Function overloading)
  2. Load operator stack (Operator overloading)

We have a separate discussion about operator overloading in C #.

Load overlap in C #

You can have multiple definitions for the same function name in the same scope. These definitions of the function must be different: such as type and / or number of parameters in the parameter list. In C #, you cannot overload function declarations but only in return types.

The following example illustrates how to use the print () function to print different data types in C #:

 using System ; namespace VdNapChong { class InDuLieu { void print ( int i ) { Console . WriteLine ( "In số nguyên: {0}" , i ); } void print ( double f ) { Console . WriteLine ( "In số thập phân: {0}" , f ); } void print ( string s ) { Console . WriteLine ( "In chuỗi: {0}" , s ); } static void Main ( string [] args ) { InDuLieu p = new InDuLieu (); // Gọi hàm in số nguyên p . print ( 9 ); // Gọi hàm in số thập phân p . print ( 501.263 ); // Gọi hàm in chuỗi p . print ( "Học C# thật vui!" ); Console . ReadKey (); } } } 

If you have read the previous C # articles, you will know, otherwise use the Console.ReadKey () command; then the program will run and finish (too fast to see the results in time). This command allows us to see the results more clearly.

Compiling and running the above C # program will produce the following results:

 Print integer: 9 
Print decimal number: 501.263
Chain printing: Learning C # is fun!

Dynamic polymorphism in C #

C # allows you to create abstract classes that are used to provide a local class implementation of an Interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods implemented by derived classes. This derived class has more specialized functions.

Here are some rules about abstract classes in C #:

  1. You cannot create an Instance of an abstract class.
  2. You cannot declare an abstract method outside an abstract class.
  3. When a sealed class is sealed, it cannot be derived, abstract classes cannot be declared sealed.

The following example illustrates an abstract class in C #: create 3 classes named Shape, HinhChuNhat and TimDienTich respectively :

 using System ; namespace VdLopAbstract {
// Lớp Shape là một lớp abstract abstract class Shape { public abstract int area (); } // Lớp HinhChuNhat là lớp dẫn xuất từ lớp Shape class HinhChuNhat : Shape { private int dai ; private int rong ; public HinhChuNhat ( int a = 0 , int b = 0 ) { dai = a ; rong = b ; } public override int area () { Console . WriteLine ( "Tính diện tích hình chữ nhật" ); return ( dai * rong ); } }
// Lớp TimDienTich chứa phương thức main() để thao tác trên HinhChuNhat class TimDienTich { static void Main ( string [] args ) { HinhChuNhat r = new HinhChuNhat ( 10 , 9 ); double a = r . area (); Console . WriteLine ( "Diện tích là: {0}" , a ); Console . ReadKey (); } } }
 

Compiling and running the above C # program will produce the following results:

 Find the area of ​​a rectangle 
Area is: 90

When you have a function defined in a class that you want to deploy a derived class, you use the virtual function in C #. Virtual functions can be deployed in different ways in different inherited classes and calling these functions will be decided at runtime.

Dynamic polymorphism in C # is implemented by abstract classes and virtual functions.

The following example illustrates this: creating 5 classes named as follows, Image, Image, Timeline, HienThiDienTich and TimDienTich.

 using System ; namespace VdLopAbstract {
// Lớp Hinh là lop abstract. class Hinh { protected int dai , rong ; public Hinh ( int a = 0 , int b = 0 ) { dai = a ; rong = b ; } public virtual int area () { Console . WriteLine ( "Diện tích của lớp cha là:" ); return 0 ; } }
// Lớp HinhChuNhat kế thừa từ lớp Hinh. class HinhChuNhat : Hinh { public HinhChuNhat ( int a = 0 , int b = 0 ): base ( a , b ) { } public override int area () { Console . WriteLine ( "Diện tích lớp HinhChuNhat là:" ); return ( dai * rong ); } }
// Lớp HinhTamGiac kế thừa từ lớp Hình class HinhTamGiac : Hinh { public HinhTamGiac ( int a = 0 , int b = 0 ): base ( a , b ) { } public override int area () { Console . WriteLine ( "Diện tích lớp HinhTamGiac là:" ); return ( dai * rong / 2 ); } }
// In dữ liệu diện tích ra màn hình. class HienThiDienTich { public void CallArea ( Hinh sh ) { int a ; a = sh . area (); Console . WriteLine ( "Diện tích: {0}" , a ); } }
// TimDienTich chứa main() thao tác với các đối tượng. class TimDienTich { static void Main ( string [] args ) { HienThiDienTich c = new HienThiDienTich (); HinhChuNhat r = new HinhChuNhat ( 10 , 7 ); HinhTamGiac t = new HinhTamGiac ( 10 , 5 ); c . CallArea ( r ); c . CallArea ( t ); Console . ReadKey (); } } }
 

Compiling and running the above C # program will produce the following results:

 Class area of ​​the image is: 
Area: 70
The area of ​​Hinh Tam's class is:
Area: 25

Follow tutorialspoint

Previous article: Calculating inheritance in C #

Next lesson: Operator overloading in C #

4.5 ★ | 2 Vote

May be interested

  • How to use GoChat application in Pokémon GOHow to use GoChat application in Pokémon GO
    pokémon go has become a very hot phenomenon since its debut. any information or tricks related to the game are read and applied by players during the process of catching pokémon. and the gochat chat app for pokémon go players brings space to capture pokémon much more interesting.
  • How to play Pokemon GO in Landscape Mode on the iPhoneHow to play Pokemon GO in Landscape Mode on the iPhone
    although players can play pokemon go in portrait mode. however, if you want to watch and play games on a large and eye-catching screen, players can switch to playing games in landscape mode.
  • The secret to controlling Pokemon Go employees at workThe secret to controlling Pokemon Go employees at work
    these days, hr managers are faced with an extremely painful problem that is the status of priority employees playing pokemon go more than work. this has caused a small impact on productivity and efficiency.
  • Check out the 'buffalo' Pokémon in Pokémon GoCheck out the 'buffalo' Pokémon in Pokémon Go
    each type of pokemon has hp, cp, ability to attack and endure differently. based on these indicators, players can determine as well as choosing the most powerful pokemon for their offensive tactics.
  • Sitting home can also locate Pokemon around, do you believe it?Sitting home can also locate Pokemon around, do you believe it?
    the tightening of the niantic developers' rules to prevent players from abusing the support tools also brings annoyance, such as those who have no conditions to move much, go away, it is hard to know. get the location of the pokemon around the area they live in
  • 5 undeniable benefits when playing Pokemon Go5 undeniable benefits when playing Pokemon Go
    get to know many new people, breathe fresh air, relieve stress, increase concentration thanks to going out for a walk .... are compelling reasons to force you to try pokemon go now .
  • Want to earn the fastest Pokécoins in Pokémon Go? So don't miss this article!Want to earn the fastest Pokécoins in Pokémon Go?  So don't miss this article!
    pokécoins in pokémon go play the role of buying items in the store. the more coins you earn, the more likely you are to buy more items. to earn pokécoins, players will have to complete certain tasks or buy real money.
  • Pokémon systems when fighting in Pokémon GoPokémon systems when fighting in Pokémon Go
    each pokémon system in pokémon go has different strengths, along with a specific weakness. this type of pokémon will have the power to attack the other pokémon, but can defeat the other pokémon. if you know the characteristics of each type, it will be easier to choose which pokémon to battle.
  • The terms you need to know when playing Pokémon GoThe terms you need to know when playing Pokémon Go
    pokémon go is the most prominent name in recent days. this game of capturing and training virtual animals has created a relatively new way of playing, as players have to constantly move to catch pokémon. during the process of joining pokémon go, you will encounter and use a lot of important terms. so what do they mean?
  • How to play Pokemon GO on Windows computersHow to play Pokemon GO on Windows computers
    recently, pokemon go has become a popular game, attracting thousands of gamers around the world. in previous posts network administrator has guided you on how to play pokemon go on android devices and ios devices. in the article below, network administrator will guide you how to play pokemon go on windows computers using bluestacks emulator software.