Overloading
and overriding are different aspects of polymorphism.
Overloading is when you define two methods
with the same name in the same class but with different signatures. Signature
includes method name and parameters. These functions can be part of base class
or derived class. Overloading is resolved at compile time.
Overloading
is also called static/early binding polymorphism. Overloading is compile time
binding.
Overriding is when you redefine a method that has already been defined in a parent class with their same signature. We can override a function in base class by creating a similar function in derived class and by use virtual/override keywords.
Overriding is when you redefine a method that has already been defined in a parent class with their same signature. We can override a function in base class by creating a similar function in derived class and by use virtual/override keywords.
Base
class method has to be marked with virtual keyword and we can override it in
derived class using override keyword.
Derived class method will completely
override base class method i.e. when we refer base class object created by
casting derived class object a method in derived class will be called.
Overriding
is mostly resolved at runtime, depending on language and situation. C++ and C#
for example, are tricky in this respect, as methods are by default not
overridable at runtime, but compile time (the virtual keyword controls this behavior).
The C# compiler will however issue warnings when it suspects you have got it
wrong.
Overriding
is also called dynamic/late binding polymorphism. Overriding is runtime
binding.
Example:
Base Class:
-------------------------------
public class BaseClass
{
public virtual void Method1()
{
Print("Base Class Method");
}
}
Derived class
-----------------------------
public class DerivedClass: BaseClass
{
public override void Method1()
{
Print("Derived Class Method");
}
}
Usage
--------------------------
public class Sample
{
public void TestMethod()
{
DerivedClass objDC = new DerivedClass();
objDC.Method1();
BaseClass objBC = (BaseClass)objDC;
objDC.Method1();
}
}
Result
---------------------
Derived Class Method
Derived Class Method
Base Class:
-------------------------------
public class BaseClass
{
public virtual void Method1()
{
Print("Base Class Method");
}
}
Derived class
-----------------------------
public class DerivedClass: BaseClass
{
public override void Method1()
{
Print("Derived Class Method");
}
}
Usage
--------------------------
public class Sample
{
public void TestMethod()
{
DerivedClass objDC = new DerivedClass();
objDC.Method1();
BaseClass objBC = (BaseClass)objDC;
objDC.Method1();
}
}
Result
---------------------
Derived Class Method
Derived Class Method
No comments:
Post a Comment