OOPs Concept - What will be the output?

Question: What will be output of the following program?
This question can be asked in many ways. So, in general i have added every thing.

Answer: See the code carefully. 

  • When you are creating object of same reference type it will always call the methods of same class. 
  • But when you are creating object of child class and assigning it to base class reference variable then only when doing overriding it will call the child class method.

using System;
 
namespace DemoApp
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            A a1 = new B();
            A a2 = new A();
            B b1 = new B();
            B b2 = (Bnew A(); //Run time error - Cast exception
 
            a1.Test1(); // A class
            a1.Test2(); // B class
            a1.Test3(); // A class
            a1.Test4(); // A class
 
            a2.Test1(); // A class
            a2.Test2(); // A class
            a2.Test3(); // A class
            a2.Test4(); // A class
 
            b1.Test1(); // B class
            b1.Test2(); // B class
            b1.Test3(); // B class
            b1.Test4(); // B class
        }
    }
 
    internal class A
    {
        public void Test1()
        {
            Console.WriteLine("Test 1 - A");
        }
 
        public virtual void Test2()
        {
            Console.WriteLine("Test 2 - A");
        }
 
        public void Test3()
        {
            Console.WriteLine("Test 3 - A");
        }
 
        public virtual void Test4()
        {
            Console.WriteLine("Test 4 - A");
        }
    }
 
    internal class B : A
    {
        public void Test1()
        {
            Console.WriteLine("Test 1");
        }
 
        public override void Test2()
        {
            Console.WriteLine("Test 2");
        }
 
        public new void Test3()
        {
            Console.WriteLine("Test 3");
        }
 
        public new void Test4()
        {
            Console.WriteLine("Test 4");
        }
    }
}

Comments

Popular posts from this blog

C# Tutorial