CoDebate

Debating Code - [ASP.NET, C#, Sql Server, VB.NET]

Saturday, December 20, 2008

Inheritance, Polymorphism and Method Hiding

Whenever I meet .NET people in the code-debate mode, I encounter a common question which is the good example for the concepts like inheritance, polymorphism and method hiding.

Check the code snippet below:
Snippet I:



public class A
{
public virtual methodA()
{
Console.WriteLine("From Class A");
}
}
public class B : A
{
public override methodA()
{
Console.WriteLine("From Class B");
}
}
public class classMain
{
public static void Main(string[] args) {
A objA = new A();
B objB = new B();

// This calls A's methodA()
objA.methodA();


// This calls B's methodA()
objB.methodA();

objA = new B();


// This calls B's methodA()
objA.methodA();
}
}


Consider the change in the Classes B and classMain, as follows:
Snippet II:



public class A
{
public virtual methodA()
{
Console.WriteLine("From Class A");
}
}


public class B : A
{
public new methodA()
{
Console.WriteLine("From Class B");
}
}


public class classMain
{
public static void Main(string[] args)
{
A objA = new A();
B objB = new B();


// This calls A's methodA()
// From the object of class A
objA.methodA();


// This calls B's methodA()
// From the object of class B
objB.methodA();


objA = new B();


// This calls A's methodA()
// From the object of class B
((A)objB).methodA();
}
}


Hope you got the execution flow and output of the above snippets.
I place some questions here:

1) In the snippet I, from the main class, if I want to call the method methodA() of class A by the object of class B, I will get compile time error. Whats the purpose of inheritance here?

2) In the snippet II, from the main class, if I am able to call methodA() of class A by the object of class B, whats the purpose of method overriding then?. (Whenever I see ILDASM, it shows two methodA() in that) .

3) Whats the significant performance improvement in using method overriding over method hiding?

Shoot your answers here...

Labels: , , , , , ,

posted by Karthikeyan @ 6:45 AM

2 Comments:

At December 27, 2008 at 6:02 AM , Blogger Srinath Gopinath said...

The method that is doing the overriding is related to the method in the base class.

Method hiding doesn't have a relationship between the methods in the base class and derived class. The method in the derived class hides the method in the base class.

I wouldn't recommend anyone to use method hiding. Method hiding couldn't give better performance compare to other.

 
At December 28, 2008 at 10:24 PM , Blogger Karthikeyan said...

Thats great srinath.. :-)

Thanks too..

Performance Optimization is one of the hot pick now.. During development, we compromize this step for various reasons.. we need to take care whenever we start coding..

Happy Programming :)

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home