Pages

Tuesday, May 6, 2014

OOPS : Polymorphism

You can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways.

http://msdn.microsoft.com/en-us/library/ms173152.aspx
http://msdn.microsoft.com/en-us/library/6fawty39.aspx

public class BaseClass
{
    public virtual void DoWork() { }
    public virtual int WorkProperty
    {
        get { return 0; }
    }
}
public class DerivedClass : BaseClass
{
    public override void DoWork() { }
    public override int WorkProperty
    {
        get { return 0; }
    }
}
DerivedClass B = new DerivedClass();
B.DoWork();  // Calls the new method.

BaseClass A = (BaseClass)B;
A.DoWork();  // Also calls the new method.
In C#, derived classes can contain methods with the same name as base class methods.
  • The base class method must be defined virtual.
  • If the method in the derived class is not preceded by new or override keywords, the compiler will issue a warning and the method will behave as if the new keyword were present.
  • If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.
  • If the method in the derived class is preceded with the override keyword, objects of the derived class will call that method instead of the base class method.
  • The base class method can be called from within the derived class using the base keyword.
  • The overridevirtual, and new keywords can also be applied to properties, indexers, and events.
class GraphicsClass
{
    public virtual void DrawLine() { }
    public virtual void DrawPoint() { }
    public virtual void DrawRectangle() { }
}
class YourDerivedGraphicsClass : GraphicsClass
{
    public override void DrawRectangle() { }
}
base.DrawRectangle(); 
Alternatively, you can prevent the warning by using the keyword new in your derived class definition:
class YourDerivedGraphicsClass : GraphicsClass
{
    public new void DrawRectangle() { }
} 
Using the new keyword tells the compiler that your definition hides the definition that is contained in the base class. This is the default behavior. 

Override and Method Selection


public class Derived : Base
{
    public override void DoWork(int param) { }
    public void DoWork(double param) { }
}
int val = 5;
Derived d = new Derived();
d.DoWork(val);  // Calls DoWork(double).

((Base)d).DoWork(val);  // Calls DoWork(int) on Derived.


MethodPreventing derived class from overriding virtual members
public class A
{
    public virtual void DoWork() { }
}
public class B : A
{
    public override void DoWork() { }
}
public class C : B
{
    public sealed override void DoWork() { }
}
public class D : C
{
    public new void DoWork() { }
}

No comments:

Post a Comment