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.
In a word, polymorphism.
By
ChildinheritingParent, the child object takes on the characteristics of the parent. If you think of it in genetic terms, it may make more sense.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.)
Because of polymorhism,
Childlooks likeParentand therefore may be instantiated asParent. Since Parent does not inherit Child, Parent does not look like Child and therefore may not be instantiated asChild.For what it’s worth, using Parent and Child have different meanings. Typically, when referring to inheritance,
Parentis the base class, whereChildwould be the derived or sub-type.