Inheritance (OOP principle)



Qus : What is Inheritance?
Ans : Inheritance is one of the primary concepts of object-oriented programming.

       => The class whose members are inherited is called the base class.
       => The class that inherits those members is called the derived class.



Qus : Why use Inheritance ?
Ans : 1. Inheritance allows us to reuse existing code.
          2. Because of reuse, we can save our programming time.


Example 001:         

    public class ParentClass
    {
        public ParentClass()
        {
            Console.WriteLine(“Parent Constructor.”);
        }

        public string Call()
        {
            return “I am a Parent Class.”;
        }
    }

    public class ChildClass : ParentClass
    {
        public ChildClass()
        {
            Console.WriteLine(“Child Constructor.”);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ChildClass oChildClass = new ChildClass();
            string a = oChildClass.Call();

            Console.WriteLine(“{0}”, a);
            Console.ReadLine();
        }
    }
    
Output :
          




Example 002 :

    public class ParentClass
    {
        public ParentClass()
        {
            Console.WriteLine(“Parent Constructor.”);
        }

        public string Call()
        {
            return “I am a Parent Class.”;
        }
    }

    public class ChildClass : ParentClass
    {
        public ChildClass()
        {
            Console.WriteLine(“Child Constructor.”);
        }

        public new string Call()  
        {
            return base.Call() + “n (I am a Parent Class.)”;  //Can call base class method by base.Call()
        }
        //N.B : new keyword of call method in child class enables this method to                                                        hide the Parentclass print() method
    }
   
     class Program
    {
        static void Main(string[] args)
        {
            ChildClass oChildClass = new ChildClass();
            string a = oChildClass.Call();

            Console.WriteLine(“{0}”, a);
            Console.ReadLine();
        }
    }

    Output : 

 

Leave a Reply