Wednesday 23 March 2011

Polymorphism Interview questions

What is Polymorphism?

Ability to provide different implementation based on different number/type of parameters that
are called by the same name.


public class DrawingShape
{
public virtual void Draw()
{
Console.WriteLine("Drawing shapes.");
}
}
public class Square : DrawingShape
{
public override void Draw()
{
Console.WriteLine("Drawing square.");
}
}
public class rectangle : DrawingShape
{
public override void Draw()
{
Console.WriteLine("Drawing rectangle.");
}
}

public class baseclass
{
public static void Main()
{
DrawingShape[] ds = new Drawingshape[2];

ds[0] = new Square();
ds[1] = new rectangle();


foreach (DrawingShape s in ds)
{
ds.Draw();
}
}
}

In this we have drawingshape class having virtual method Draw() whic his overriden in the Square and rectangle class.


In which cases you use override?

If the base class member is declared as virtual or abstract then to override these members in derived class
we use override leyword in derived class.

Can you override private virtual methods?

No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access

What does the keyword virtual mean in the method definition?

It means the method can be over-ridden in derived class.

Can you declare the override method static while the original method is non-static?

No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

How a base class method is hidden?

We can Hide a base class method by declaring a method in derived class with keyword new.

What is the difference between virtual and abstract method?

Abstract methods doesnot provide implementation of method whereas virtual method provides the implementation.

No comments:

Post a Comment