NenTang.vn
.NETLập trình căn bản C#
Tính đa hình trong C#
Hướng đối tượng trong C#
Thời lượng: 81 phútĐọc khoảng: 4 phút
Từ viết tắt
Nội dung bài học không khai báo từ viết tắt bằng thẻ abbr.
Nội dung bài học
The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.
Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.
When the above code is compiled and executed, it produces the following result −
When the above code is compiled and executed, it produces the following result −
When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
The following program demonstrates this −
When the above code is compiled and executed, it produces the following result −
Static Polymorphism
The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are −- Function overloading
- Operator overloading
Function Overloading
You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type. The following example shows using function print() to print different data types −csharp
shellscript
Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality. Here are the rules about abstract classes −- You cannot create an instance of an abstract class
- You cannot declare an abstract method outside an abstract class
- When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
csharp
shellscript
csharp
shellscript

