Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Polymorphism potx
Nội dung xem thử
Mô tả chi tiết
Polymorphism
Chapter 7
Polymorphism is the ability that helps in executing
different operations in response to the same
message. In OOP, you can implement
polymorphism by creating more than one function
within a class that have the same name. The
difference in the functions lies in the number and the
types of parameters passed to each function.
This chapter introduces the concept of
polymorphism. It explains how to implement
function overloading and operator overloading.
In this chapter, you will learn to:
Describe polymorphism
Implement function overloading
Implement operator overloading
Objectives
¤NIIT Polymorphism 7.3
The term polymorphism was derived from the Greek words ‘poly’ and ‘morphos’, which
mean ‘many’ and ‘forms’, respectively. In OOP, polymorphism is often expressed by the
phrase “one interface, multiple functions”. This expression means that polymorphism
allows one interface to be used for multiple functions. You can apply polymorphism for
reducing the complexity within the functions of a class of your program.
Polymorphism can either be static or dynamic. In static polymorphism the response to a
function is decided at compile time. In dynamic polymorphism the response to the
function is decided at run time.
Static polymorphism refers to an entity, which exists in various forms simultaneously.
The concept of static polymorphism is analogous to the role of a woman who can be a
wife, a mother, a daughter, a sister, and an executive at the same time.
The mechanism of linking a function with an object during compile time is called early
binding. It is also known as static binding.
C# uses two approaches to implement static polymorphism. These are:
Function Overloading
Operator Overloading
Function Overloading
This approach allows using the same name for two or more functions. Each redefinition of
a function must use different types of parameters, sequence of parameters, or a number of
parameters. The type, sequence, or number of parameters for a function is called the
function signature. When you have multiple functions with the same name, the compiler
identifies the function based on the parameters to the function.
Consider an example, to understand the benefit of function overloading where you need a
function that converts distance in kilometers to miles, and kilometers can either be an
integer or a float. One approach can be to have two functions of different names, as
shown in the following code:
int ConvertInteger(int km);
int ConvertFloat(float km);
Introducing Polymorphism
Static Polymorphism