Polymorphism: Polymorphism is one name many forms.
Def: "Implementing multiple functionality with the same name can be called as polymorphism that means implementing multiple functions with same name can be called as polymorphism"
We can achieve polymorphism in 2 ways. 1. Function overloading 2. Function overriding
1. Function overloading: Function overloading means having multiple methods with the same name but a different number of arguments or different type of arguments in a single class or a combination of base & derived class.
Eg: For function overloading namespace functionoverloadingexample { Public class calculate { Public int add(int a, int b) { return a + b; } Public int add(int a , int b, int c) { return a+b+c; } Public double add(double a, double b) { return a + b; } Public double add(double a , double b, double c) { return a+b+c; }
Class mainclass { Void main() { Calculate cal = new calculate(); int res1 = cal.add(10, 20); Console.WriteLine("addition of two integers is " +res1); int res2 = cal.add(10, 20, 30); Console.WriteLine("Addition of 3 integers is " +res2) double res3 = cal.add(10.4, 20.5); Console.WriteLine("addition of two double is " +res3); int res4 = cal.add(10.4, 20.5, 30.5); Console.WriteLine("addition of 3 double is " +res4); Console.ReadLine(); } } } Output: addition of two integer is 30 addition of 3 integer is 60 addition of 2 double is 30.9 addition of 3 double is 61.4
Function overloading will depend on below 3 points 1. Type of parameter to a function 2. Number of parameter to a function 3. Order of parameter to a function
Function overloading will not depend on below two points. 1. return type of a function. 2. Name of parameter to a function
Function overloading will depend on 1. Type of parameter to a function: namespace typeofparameterexample { Public class myclass { Public void print(int a) { Console.WriteLine("a value is " +a); } Public void print(String s) { Console.WriteLine("S avalue is " +s); }
Class mainclass { Void main() { myclass mc = new myclass(); mc.print(10); mc.print(Sathya); Console.ReadLine(); } } } Output: a value is 10 s value is Sathya.