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?
Labels: C#, C# Interview Questions, Inheritance, Method Hiding, overriding, Polymorphism, virtual