Today I’m working on a school project of Software Design which need to use OOP, so I decide to write a small article about Constructor and Inheritance in C#
When initializing new object of a subclass, constructor of the parent class will be called first, after that constructor of the subclass will be called.
For example, I have Base and Child class (inherited from Base) as follows:
Run the program, you’ll see the constructor of the Base has been called first!
We can check other cases:
- Make Base class abstract.
main()function, initialize the object using
Child c = new Child()
All produce similar results.
Now try with another special case, add new constructor containing parameter to the Base and Child class:
Run the program. Here, even when we’re initializing new object of Child class using constructor with parameters, the default constructor (no-arg constructor) of the Base class is always called.
Now, if you delete the default constructor of Base class and run program again, you’ll receive compile error immediately.
When new object of a class initializing, if that class doesn’t have any constructor, C# will automatically generate a default constructor (no-arg constructor).
Why? Because if C# don’t generate, we won’t be able to create any object of that class.
However, if you manually create new constructor (with parameter) and delete the default constructor, C# will assume that your class can now create new object by itself and won’t generate default constructor anymore. That why objects created by calling
new Base() will failed to compile.
Child calls their parent
In addition, when initializing a Child object, C# will automatically call the default constructor of the parent Base class first, after that constructor of the subclass will be called.
Why is that?
In my opinion, just imagine the subclass is a “concretization” of parent class.
Like a car, before it becomes a real vehicle, it must go through process of being the chassis, the Chassis is the parent. To create the chassis, we must use the constructor of the Chassis, which will call the assembly, welding functions,.. After the chassis is finished, we call the constructor of the Car to call the wheels, saddle,.. assembly functions — which helps form a complete car!
So the calling order is really logical and practical, right?
Change calling orders
However, if you want to call the specific constructor (not the default constructor) of the parent class, you could use the keyword
base() after declaration of your constructor:
One more thing
I would like to say, generally in Java the constructor of the parent class will also be called automatically when initializing the object of the subclass. You can see more here.