Tuesday, 14 February 2012

polymorphism


Polymorphism is the process of defining more functionality with same name with in the class. Polymorphism is a process of one form available in different forms. We have two different types of polymorphism,

1) Compile time polymorphism/static polymorphism (overloading)

2) Runtime polymorphism/dynamic polymorphism (overriding)

Compile time polymorphism (overloading):

Compile time polymorphism is defining more functionality with the same name in the class but difference in the signature of the method. Signature of the method means the order and the type of method arguments.

In this, multiple methods declared with same name but signature will be different. The compiler decides which method will execute in compile time, so it is known as compile time polymorphism.

The main advantage of this type is execution is fast.

Overloading a method simply involves another method with the same name with in the class

Example:

Class A

{

Public void display ()

{

Console.writeLine (“this is first method”);

}

Public void display (int a, int b)//method overloading

{

Console.writeLine (“this is second method”);

}

Public void display (int a, float b)

{

Console.writeLine (“this is third method”);

}

}

Class program

{

Public static void main (string [] args)

{

A x=new A ();

x.display ();

x.display (5, 8.4);

x.display (2, 4);

}

}

Runtime polymorphism (overriding):

Runtime polymorphism is defining more functionality with the same name and same signature in the derived class.

In this, base class method is override in derived class with the keyword ‘override’. The compiler decides which method will execute in runtime, so it is known as runtime polymorphism.

Overriding occurs when a derived class has a method with same signature as a base class’s method.

The ‘base’ keyword is used to access the base method that has been overridden.

Example:

Class A

{

Public virtual void display ();

}

Class B : A

{

Public override void display ()

{

Console.writeLine (“this is class B’s method”);

}

Class C : A

{

Public override void display ()

{

Console.writeLine (“this is class C’s method”);

}

Class program

{

Public static void main (string [] args)

{

B b=new B ();

b.display ();//calls class B’s method

C c=new C ();

c.display ();// calls class C’s method

}

}

No comments:

Post a Comment