Polymorphism potx

32 93 0
Polymorphism potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

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 7.4 Polymorphism ¤NIIT N ote Another approach can be using function overloading. You can have two functions with the same name but with different parameters, as shown in the following code: int Convert(int km); float Convert(float km); Operator Overloading This approach allows user-defined types such as structures and classes, to use overloaded operators for easy manipulation of their objects. Operator overloading can be achieved by defining the static member functions using the operator keyword. For example, you can redefine the + operator for a user-defined class Hour to add the hour value of two class objects. You can then add two Hour objects by using the + operator. The following code is an example showing the usage of operator (+): Hour h1; Hour h2; Hour h3; H3=H1+H2; In dynamic polymorphism the decision about function execution is made at run time. Dynamic polymorphism is more useful as compared to static polymorphism because dynamic polymorphism gives much more flexibility for manipulating objects. The mechanism of linking a function with an object at run time is called dynamic or late binding. Dynamic binding supports virtual functions. C# uses two approaches to implement dynamic polymorphism. These are:  Abstract classes: Are the special type of base classes that consist of abstract class members. All the class members that are derived directly from abstract classes must implement all the abstract functions and properties.  Virtual functions: Are the functions that do not really exist, however, appear to be present in some parts of the program. Abstract classes and virtual functions will be taught in detail in chapter 8. Dynamic Polymorphism ¤NIIT Polymorphism 7.5 Function overloading is the most common way of implementing polymorphism. You can implement function overloading by defining two or more functions in a class sharing the same name. However, each definition of a function must differ in its function signature. The following code is an example of function overloading: using System; namespace CalculateMax { class CalculateMax { public int Max(int number1, int number2) { if (number1 > number2) { return number1; } else { return number2; } } public float Max(float number1, float number2) { if (number1 > number2) { return number1; } else { return number2; } } } class MaxCalc { static int Main(string[] args) { CalculateMax calc = new CalculateMax(); Console.WriteLine("{0}", calc.Max(5.4F, 8.6F)); //Both function calls differ Console.WriteLine("{0}", calc.Max(19, 12)); //only in their parameters Console.ReadLine(); return 0; } } } Implementing Function Overloading 7.6 Polymorphism ¤NIIT In the preceding example, the function Max() displays the maximum of two numbers, number1 and number2. The function Max() is overloaded by passing the integer and float values to it. The output of the preceding code is as follows. Output of the Function Overloading Program During a function call, a C# compiler needs to resolve the name of the function. The signature of a function is defined by:  The number of parameters. Consider the following example: void AddNumber(int); void AddNumber(int, float); In the preceding code, there are two functions because the number of parameters is different.  The data types of parameters. Consider the following example: void Display(int); void Display(char); In the preceding code, the two functions are different because the data type of their parameters is different.  The sequence of the parameters. Consider the following example: void Display(int,char); void Display(char,int); Function Signature ¤NIIT Polymorphism 7.7 N ote In the preceding code, the two functions are different because their parameters are specified in a different order. The return type is NOT a part of a function's signature. Therefore, the following two declarations cannot occur in the same class: void display(); char display(); In addition to function overloading, you can also overload constructors. Constructors can also be parameterized, and therefore, they can be overloaded. Overloaded constructors are commonly used in C# to provide flexibility while creating an object. The following is an example of overloading constructors: using System; class CalculateNumber { private int number1, number2, total; //Default constructor public CalculateNumber() { number1= number2= total = 0; } public CalculateNumber(int num1, int num2) //Two-argument //constructor { number1= num1; number2= num2; total = 0; } public void AddNumber() { total = number1 + number2; } public void DisplayNumber() { Console.WriteLine("The sum of two numbers is {0}", total); } } class CalNum { Constructor Overloading 7.8 Polymorphism ¤NIIT N ote static int Main(String[] args) { //Default constructor invoked CalculateNumber cal1 = new CalculateNumber(); //Parameteric constructor CalculateNumber cal2 = new CalculateNumber(4,3); cal1.AddNumber(); //add() invoked to calculate sum of members cal1.DisplayNumber(); cal2.AddNumber(); //add() invoked to calculate sum of members cal2.DisplayNumber(); return 0; } } In the preceding code, the default constructor is invoked for object cal1 because it is created without any parameter. The parameterized constructor is invoked for cal2 object because it is created with parameters. To see the output of the preceding program, press Ctrl+F5. The output of the preceding code is as follows. Output of the Constructor Overloading Program ¤NIIT Polymorphism 7.9 Problem Statement Tim has to develop an application for a primary school. The application should accept the month entered by the student and display the total number of days of that month. Solution To develop the required application, Tim needs to perform the following tasks: 1. Create a console-based application. 2. Build and execute an application. Task 1: Creating a Console-Based Application To create a console-based application, Tim needs to perform the following steps: 1. Select StartÆAll ProgramsÆMicrosoft Visual Studio 2005ÆMicrosoft Visual Studio 2005. The Start Page - Microsoft Visual Studio window is displayed. 2. Select FileÆNewÆProject. The New Project dialog box is displayed. 3. Select the project type as Visual C# from the Project types pane and Console Application from the Templates pane. 4. Type the name of the new project as PrimarySchool in the Name text box. 5. Specify the location where the new project is to be created as c:\chapter7\Activity1 in the Location combo box. 6. Click the OK button. 7. Open the Solution Explorer window and right-click the Program.cs file. The shortcut menu is displayed. 8. Select the Rename option and type the new name as DayCount.cs. 9. Double-click the DayCount.cs file in the Solution Explorer window. The Code view of the DayCount.cs file is displayed. 10. Replace the existing code with the following code: using System; namespace PrimarySchool { class DayCount { int Month; int Year; int Days; Activity: Displaying Days Using Function Overloading 7.10 Polymorphism ¤NIIT public DayCount() //Constructor to initialize month and year to 0 { Month = 0; Year = 0; } //Returns 1 if year is a leap year, else returns 0 public Boolean LeapYear() { if (Year % 4 == 0) return true; else return false; } //Sets the month and year public void setDate(int month1, int year1) { Year = year1; Month = month1; } // Sets the month, overloaded function public void setDate(int month1) { Month = month1; Year = 2006; } //Returns the name of the month public string monthName() { switch (Month) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; default: return "Invalid Month Specified!"; } } //Sets the number of days in a month public void setDays() { switch (Month) [...]... application 7.26 Polymorphism NIIT The following window verifies the output of the executed program Output of the FunCityLand Application NIIT Polymorphism 7.27 Practice Questions 1 Which of the following options about implementing polymorphism is NOT true? a You can implement polymorphism by implementing an interface b You can also achieve polymorphism by inheritance c You can implement polymorphism by... false 7.28 Polymorphism NIIT 5 NIIT Which of the following statements is true about operator overloading? a The + operator cannot be overloaded b Binary operators are operators that work with two operands Polymorphism 7.29 Summary In this chapter, you learned that: The term polymorphism has been derived form the Greek words ‘poly’ and ‘morphos’, which mean ‘many’ and ‘forms’, respectively Polymorphism. .. that a binary operator requires an additional parameter 7.30 Polymorphism NIIT Exercises Exercise 1 Write a program, which accepts the number of pages you want to add in the book The program should further increment the number of pages of a book by the number of pages entered by the user Hint: Use operator overloading NIIT Polymorphism 7.31 7.32 Polymorphism NIIT ... the Greek words ‘poly’ and ‘morphos’, which mean ‘many’ and ‘forms’, respectively Polymorphism allows one interface to be used for multiple functions Static polymorphism refers to an entity, which exists in different forms simultaneously In dynamic polymorphism the decision about function execution is made when code is executed Function overloading is the process of using the same name for two or more... by implementing an interface b You can also achieve polymorphism by inheritance c You can implement polymorphism by encapsulation d You can implement polymorphism by using abstract classes 2 Consider the following statements: Statement A: In dynamic polymorphism, appropriate methods of a program can be invoked, depending on the context Statement B: In early binding, function calls are bound at run... Console.ReadLine(); } } class EntryPoint { static void Main() { Calculator calc = new Calculator(15, -25); //using the overloaded – operator with the class object calc = -calc; calc.Print(); } } } 7.16 Polymorphism NIIT The output of the preceding example is as follows Output of the – Operator Overloading Program In the preceding code, - operator is overloaded to make the variables of class Calculator... notations must be public, static, and unary The following is an example of the increment operator for the Watch struct: struct Watch { private int val; public static Watch operator++ (Watch parameter) { NIIT Polymorphism 7.17 } parameter.val++; return parameter; } In C#, the single operator is used for both the prefix and postfix operators The result of a postfix notation is the value of the operand before... ++(NumberCount arg) { arg.i++; return arg; } } class TestClass { static void Main(string[] args) { NumberCount Count1 = new NumberCount(1); NumberCount Count2 = Count1++; Console.WriteLine(Count1.i); 7.18 Polymorphism NIIT Console.WriteLine(Count2.i); Count2 = ++Count1; Console.WriteLine(Count1.i); Console.WriteLine(Count2.i); Console.ReadLine(); } } } The output of the preceding example is as follows Output... structs cannot be implemented with classes If Watch is a class, assigning of variable w to postFix makes the variable postFix refer to the same object as w Updating w will automatically update postFix NIIT Polymorphism 7.19 The following is an example of the implementation of the increment operator where Watch is a class: class Watch { private int val; { } public Watch(int paraVal) this.val = paraVal; public... TestClass { static void Main(string[] args) { NumberCount Count1 = new NumberCount(1); NumberCount Count2 = Count1++; Console.WriteLine(Count1.i); Console.WriteLine(Count2.i); Count2 = ++Count1; 7.20 Polymorphism NIIT } Console.WriteLine(Count1.i); Console.WriteLine(Count2.i); Console.ReadLine(); } } The output of the preceding example is as follows Output of the Overloading Increment Operator Program . H3=H1+H2; In dynamic polymorphism the decision about function execution is made at run time. Dynamic polymorphism is more useful as compared to static polymorphism because dynamic polymorphism gives. 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. 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

Ngày đăng: 01/08/2014, 09:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan