Thursday 2 February 2012

Polymorphism


Polymorphism



Polymorphism means same operation may behave differently on different classes.
Eg:
Method Overloading is an example of Compile Time Polymorphism.
Method Overriding is an example of Run Time Polymorphism
Does C#.net supports multiple inheritance?
No. A class can inherit from only one base class, however a class can implements many interface, which servers some of the same purpose without increasing complexity.
How many types of Access Modifiers.
1) Public – Allows the members to be globally accessible.
2) Private – Limits the member’s access to only the containing type.
3) Protected – Limits the member’s access to the containing type and all classes derived from the containing type.
4) Internal – Limits the member’s access to within the current project.



Method Overloading


Method with same name but with different arguments is called method overloading.
Method Overloading forms compile-time polymorphism.
Eg:
class A1
{
void hello()
{ Console.WriteLine(“Hello”); }
void hello(string s)
{ Console.WriteLine(“Hello {0}”,s); }
}

Method Overriding


Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
Method overriding forms Run-time polymorphism.
Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.
Eg1:
Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}
Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}
static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.

Virtual Method



By declaring base class function as virtual, we allow the function to be overridden in any of derived class.
Eg:
Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}
Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}
static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.

No comments:

Post a Comment