Monday, 5 August 2013

Overloading and Overriding of the Class

Overloading and Overriding of the Class
Overloading provides the ability to create multiple methods or properties with the same
name, 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. 
 
 
using System;
public class test
{
public int Add(int x , int y)
{
return(x + y);
}
public string Add(String x, String y )
{
return (x + y);
}
public static void Main()
{
test a = new test ();
int b;
String c;
b = a.Add(1, 2);
c = a.Add("Reshmi", " Nair");
Console.WriteLine(b);
Console.WriteLine(c);
}
}
O/P:
3
Reshmi Nair
 
 
 
 
Overriding 
 
Class inheritance causes the methods and properties present in the base class also to be
derived 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.
public abstract class shapes
{
public abstract void display()
{
Console.WriteLine("Shapes");
}
}
public class square: shapes
{
public override void display()
{
Console.WriteLine("This is a square");
}
}
public class rectangle:shapes
{
public override void display()
{
Console.WriteLine("This is a rectangle");
}
}
The above example is just an indication to how overriding can be implemented in C#.
 
 

No comments:

Post a Comment