Function overloading
Function overloading means more than one function with same name and different signature. i.e. function name same and parameter are different. These function can be exist in the same class or in the base and derive class.Method overloading is the example of compile time polymorphism
Example
class FunctionOverloading{
//function GetName with one parameter.
public string GetName(string name)
{
return "My name is :- " + name;
}
//function GetName with two parameter.
public string GetName(string firstName, string lastName)
{
return "My name is :- " + firstName + " " + lastName;
}
//function GetName with three parameter.
public string GetName(string firstName, string lastName, string surname)
{
return "My name is :- " + firstName + " " + lastName + " " + surname;
}
}
class Program
{
static void Main(string[] args)
{
FunctionOverloading obj = new FunctionOverloading();
string name = obj.GetName("Ram");
Console.WriteLine(name);
name = obj.GetName("Ram", "Kumar");
Console.WriteLine(name);
name = obj.GetName("Ram", "Kumar", "Verma");
Console.WriteLine(name);
}
}
Output
My name is :- RamMy name is :- Ram Kumar
My name is :- Ram Kumar Verma
Function overriding
Function overriding means two function with the same name and same signature, one method in base class and another one in derive class.We have to use virtual and override keywords with the function. Virtual keyword in the base class and override in the derive class.
Function overriding is the example of run time polymorphism.is the example of run time polymorphism.
Example
// Base class
class Parent{
public virtual int Calculation(int i, int j)
{
return i * j;
}
}
// Derive class
class child : Parent
{
public override int Calculation(int i, int j)
{
return i / j;
}
}
class Program
{
static void Main(string[] args)
{
Parent obj = new Parent();
int i = obj.Calculation(20, 10);
Console.WriteLine(i);
Parent obj1 = new child();
int j = obj1.Calculation(20, 10);
Console.WriteLine(j);
}
}
Output
2002
More ....Interview Questions and answers
ReplyDeleteLing
Excellent explanation Difference Between Method Overloading and Method Overriding
ReplyDelete