I am relatively new to OOP, so I wanted to clarify a few things
I have the following code snippet
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 constructor of the base class called when creating objects using the constructor ChildClass? without explicit keyword base. Is there a way to avoid calling the base class constructor?
2) why is it possible ParentClass ParentObj = new ChildClass();? and not vice versa.
source
share