Polymorphism
Polymorphism is nothing but overloading with different parameters. It is same name as other methods in same program but different parameters or arguments passed to it.
Polymorphism is the third pillar of OOP (Object Oriented Programming) language.
Or in simple terms “One interfaces multiple functions”.
How to define polymorphism in C#?
public void Draw() { //Code } public void Draw(int x1) { //Code } public void Draw(int x1, int y1) { //Code }
Example:
using System; class Program { static void Main() { Shape sp = new Shape(); //Draw with x:10 and Y:10 sp.Draw(10); //Draw with x:10 and y:20 sp.Draw(10, 20); } } class Shape { private int x, y; public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public void Draw() { Console.WriteLine("Draw X: {0} Y: {1}", x, y); } public void Draw(int x1) { X = x1; Y = x1; this.Draw(); } public void Draw(int x1, int y1) { X = x1; Y = y1; this.Draw(); } }
Output:
Draw X: 10 Y: 10
Draw X: 10 Y: 20
Press any key to continue…
In above example you can see that Draw method is created three times but with different parameters.
There is two types of polymorphism.
- Static polymorphism
- Dynamic polymorphism
you can also visit: www.mybook-lang.com
No comments:
Post a Comment