Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance doubts

Tags:

c#

inheritance

I'm relatively new to OOP, so wanted to clear a few things,

I have the following piece of code

class Parent
{
     public Parent()
     {
           Console.WriteLine("Parent Class constructor");
     }

     public void Print()
     {
            Console.WriteLine("Parent->Print()");
     }
}

class Child : Parent
{
     public Child() 
     {
          Console.WriteLine("Child class constructor");
     }

     public static void Main()
     {
           Child ChildObject = new Child();
           Parent ParentObject = new Child();

           ChildObject.Print();
           ParentObject.Print();
     }

}

Output :

Parent Class Constructor
Child Class constructor

Parent Class Constructor
Child Class constructor

Parent->Print()
Parent->Print()

My questions are as follows :

1) Why is the base class constructor called when I instantiate objects with the ChildClass constructor? without explicitly specifying the base keyword. Is there any way to avoid calling the base class constructor?

2) why is ParentClass ParentObj = new ChildClass(); possible? and not the other way round.

like image 916
jack Avatar asked Aug 16 '11 20:08

jack


2 Answers

  1. All base class constructors all the way up inheritance tree will get called. Constructors are always chained starting with the parent class on down to the most derived class.

  2. Instances of ChildClass "are" instances of ParentClass. They model an "is-a" relationship, but not the other way around.

like image 102
FishBasketGordo Avatar answered Sep 30 '22 03:09

FishBasketGordo


In a word, polymorphism.

By Child inheriting Parent, the child object takes on the characteristics of the parent. If you think of it in genetic terms, it may make more sense.

1) Why is the base class constructor called when I instantiate objects with the ChildClass constructor? without explicitly specifying the base keyword. Is there any way to avoid calling the base class constructor?

There is no way to get around the base class constructor being called (that I am aware of). The point of having the base class constructor called is to instantiate the base class (pass parameters, initialize other objects, assign values, etc.)

2) why is ParentClass ParentObj = new ChildClass(); possible? and not the other way round.

Because of polymorhism, Child looks like Parent and therefore may be instantiated as Parent. Since Parent does not inherit Child, Parent does not look like Child and therefore may not be instantiated as Child.

For what it's worth, using Parent and Child have different meanings. Typically, when referring to inheritance, Parent is the base class, where Child would be the derived or sub-type.

like image 23
IAbstract Avatar answered Sep 30 '22 02:09

IAbstract