Sunday, 1 April 2018

Inheritance Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplicationSecondTry
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             * We have two classes A and B.
             * Class B inherits class B.
             * if we create object of class A ( Which points to the class A  // A O = new A(); // ) then
             * We can call and access the base class (Class A) Methods and data members
             */
            A O = new A();
            O.Method_In_A();
            O.a = 20;

            /*
             * We have two classes A and B.
             * Class B inherits class B.
             * if we create object of class A ( Which points to the class B  // A O1 = new B(); // ) then
             * We can call and access the base class (Class A) Methods and data members
             * In this case the constructor of base class is called and we can assign the value to base class public data members(Inheritance - Is relationship ).
             */
            A O1 = new B();
            O1.a = 30;
            O1.Method_In_A();

            /*
             * We have two classes A and B.
             * Class B inherits class B.
             * if we create object of class B ( Which points to the class B  // B O2 = new B(); // ) then have access to all public methods and data members.
             */
            B O2 = new B();
            O2.a = 50;
            O2.b = 60;
            O2.Method_In_A();
            O2.Method_In_B();

            /*
             * We have two classes A and B.
             * Class B inherits class B.
             * if we create object of class B ( Which points to the class A  // B O3 = new A(); // ) then we get error as an explicit conversion exist (Inheritance concept).
             * below line will not work.
             */
            //B O3 = new A();

            Console.ReadLine();
        }
    }

    class A
    {
        public int a = 10;
        public A()
        {
            Console.WriteLine("Constructor Of A");
        }
        public A(int i)
        {
            i = a;
            Console.WriteLine("Param Constructor Of A", i);
        }

        public void Method_In_A()
        {
            Console.WriteLine("Method in A Called.");
        }
    }
    class B : A
    {
        public int b = 10;
        public B()
        {
            Console.WriteLine("Constructor Of B");
        }
        public B(int i)
        {
            i = b;
            Console.WriteLine("Param Constructor Of B", i);
        }
        public void Method_In_B()
        {
            Console.WriteLine("Method in B Called.");
        }
    }
}


No comments:

Post a Comment