Thursday, November 20, 2008

Polymorphism:

function Overloading:

The declaration of the method name will be same, but passing parameter datatypes, order of parameters and number of parameters will be differentiate the methods.

In the belowed example, Add method is doing different operations. Here in this example i have implemented the Constructor Overloading also.

using System;
using System.Collections.Generic;
using System.Text;

namespace Polymorphism
{
class Sample
{
public Sample()
{
Console.WriteLine("Sample Constructor invoked");
Console.ReadLine();
}
public void Multiply()
{
int a, b, c;
a = 10;
b = 20;
c = a * b;
Console.WriteLine("C value is:" + c);
Console.ReadLine();
}
public void Exam()
{
Console.WriteLine("This is from base calss");
Console.ReadLine();
}

public virtual void display()
{
Console.WriteLine("Hello from Base class");
Console.ReadLine();
}

}
class Program:Sample
{
public Program()
{
Console.WriteLine("Program constructor involked");
Console.ReadLine();
}
public void Multiply(int a, int b)
{
int c = a * b;
Console.WriteLine("C value is:" + c);
Console.ReadLine();
}
public new void Exam()
{
Console.WriteLine("This is from Derived class");
Console.ReadLine();
}
public int Add(int n1, int n2)
{
return n1 + n2;
}
public float Add(float a1, float a2)
{
return a1 + a2;
}
public override void display()
{
Console.WriteLine("Hello from derived class");
Console.ReadLine();
}
static void Main(string[] args)
{
Program pgm = new Program();
pgm.display();
pgm.Exam();
pgm.Multiply(20, 30);
pgm.Multiply();
Console.WriteLine(pgm.Add(2.3f, 5.6f));
Console.WriteLine(pgm.Add(45, 67));
Console.ReadLine();
Sample obj = new Sample();
obj.Multiply();
obj.display();
obj.Exam();
Sample pgm1 = new Program();
pgm1.display();
pgm1.Exam();
pgm1.Multiply();
}
}
}

No comments: