Overloading
Overloading provides the ability to create multiple methods or properties with the samename, but with different parameters lists. This is a feature of polymorphism. A simple
example would be an addition function, which will add the numbers if two integer
parameters are passed to it and concatenate the strings if two strings are passed to it.
Example:-
using System;
public class test
{
public int Add(int a , int b)
{
return(a + b);
}
public string Add(String a, String b )
{
return (a + b);
}
public static void Main()
{
test x = new test ();
int y;
String z;
y = x.Add(1, 2);
z = x.Add("Merbin", " Joe");
Console.WriteLine(y);
Console.WriteLine(z);
}
}
public class test
{
public int Add(int a , int b)
{
return(a + b);
}
public string Add(String a, String b )
{
return (a + b);
}
public static void Main()
{
test x = new test ();
int y;
String z;
y = x.Add(1, 2);
z = x.Add("Merbin", " Joe");
Console.WriteLine(y);
Console.WriteLine(z);
}
}
Output:-
3
Merbin Joe
Merbin Joe
Overriding
Class inheritance causes the methods and properties present in the base class also to bederived into the derived class. A situation may arise wherein you would like to change
the functionality of an inherited method or property. In such cases we can override the
method or property of the base class. This is another feature of polymorphism.
Example:-
public abstract class sample
{
public abstract void display()
{
Console.WriteLine("Sample");
}
}
public class square: sample
{
public override void display()
{
Console.WriteLine("This is a square");
}
}
public class rectangle:sample
{
public override void display()
{
Console.WriteLine("This is a rectangle");
}
}
{
public abstract void display()
{
Console.WriteLine("Sample");
}
}
public class square: sample
{
public override void display()
{
Console.WriteLine("This is a square");
}
}
public class rectangle:sample
{
public override void display()
{
Console.WriteLine("This is a rectangle");
}
}
Advertisement
0 comments:
Post a Comment