Polymorphism is major concept of
object programming and in general term, it stands for ‘Many Shape’, it means the
one function can perform different thing depend on context.
In C#, Polymorphism can be categories
in two group.
·
Static Polymorphism
·
Dynamic Polymorphism
Static Polymorphism:
In Static polymorphism,
the calling method will be decided on compile time so it is also called Early
Binding. In C#, it will be achieved by Function Overloading or Operator
Overloading
Function Overloading:
we can defined multiple function with same name but its signature will be different,
it is called function overloading. In method signature, we are not considering
return type.
The following code
shows How same function ‘Render()’
render different shape based on passed input type ( Circle, Rectangle).
public class RenderShape
{
public void Render(Circle circle)
{
Console.Writeline("Rendering Circle");
}
public void Render(Rectangle rectangle)
{
Console. Writeline
("Rendering Rectangle");
}
}
public class RenderEngine
{
public void Render()
{
RenderShape
renderShape = new
RenderShape();
renderShape.Render(new
Circle());
renderShape.Render(new
Rectangle());
}
}
Output:
Rendering
Circle
Rendering
Rectangle
Dynamic
Polymorphism –
In Dynamic
polymorphism, the calling method will be decided on runtime so it is also
called Late Binding. In C#, it will be achieved
by implementation of Abstract Class or Interface.
Abstract:
In C#, Abstract
class is used for partial implementation and it contains abstract method, which
must be implemented by derived class eg. Circle, Rectangle. Abstract class
can have some common code, which will be shared among all derived class.
public abstract class Shape
{
public abstract void
Render();
}
public class Circle : Shape
{
public override void Render()
{
Console.Write("Rendering Circle");
}
}
public class Rectangle : Shape
{
public override void Render()
{
Console.Write("Rendering Rectangle");
}
}
public class RenderEngine
{
public void Render()
{
Shape shape
= new Circle();
shape.Render();
shape = new Rectangle();
shape.Render();
}
}
Interface:
Interface is a basically contract, which have only signature of methods or property. the class which will be implement this interface have to define the signature.
Interface is a basically contract, which have only signature of methods or property. the class which will be implement this interface have to define the signature.
public interface IShape
{
void Render();
}
public class Circle : IShape
{
public void Render()
{
Console.Write("Rendering Circle");
}
}
public class Rectangle : IShape
{
public void Render()
{
Console.Write("Rendering Rectangle");
}
}
public class RenderEngine
{
public void Render()
{
IShape shape
= new Circle();
shape.Render();
shape = new Rectangle();
shape.Render();
}
}
Thanks for visiting !!
No comments:
Post a Comment