Method overloading | Method overriding |
method overloading used to achieve “early binding” or “static binding”. | method overriding used to achieve “late (dynamic) binding” or “runtime polymorphism”. |
method overloading means, in a class method can be declared with same method name and with different parameters. | method overriding means, a method defined in base class can be redefined in the derived classes. |
method signature (method name + parameter) must be different in method overloading. | method signature must be same in method override. |
Sample Program:
using system;Output:
using system.collections.generic;
using system.text;
namespace consoleapplicationc
{
//Base class
class baseclass
{
private int add(int a, int b)
{
return a + b;
}
// Overload the Above Method
private float add(float a, float b)
{
return a + b;
}
// virtual method - Indicates this will be override in Child class
public virtual string whereiam()
{
return "In Base Class";
}
}
// Derived Class
class derived : baseclass
{
// Base class Method Override here
public override string whereiam()
{
return "In Derived Class";
}
}
class program
{
static void main(string[] args)
{
// Just create base class reference
baseclass basereference;
// Create Base class Object
baseclass baseobj = new baseclass();
// create object for Derived class
derived derivedobj = new derived();
// Base class reference contains derived object
basereference = derivedobj;
// Now Derived class method called with base ref
string strvalue = basereference.whereiam();
console.writeline(strvalue);
// Now Base class ref contains base object
basereference = baseobj;
string strval = basereference.whereiam();
console.writeline(strval);
console.read();
}
}
}
in derived class
in base class
0 comments :