Constructor Calls in Inheritance
Case study 1:
ClassA is a base class of ClassB.
Both classes have default constructor.
Observations:
While creating a new instance of ClassB (without parameters):
- it will first call default constructor of ClassB which will call constructor of ClassA.
- it will complete executing code of default constructor of ClassA.
- after that, it will complete executing code of default constructor of ClassB.
While creating a new instance of ClassB (without parameters):
- it will first call default constructor of ClassB which will call constructor of ClassA.
- it will complete executing code of default constructor of ClassA.
- after that, it will complete executing code of default constructor of ClassB.
Case study 2:
ClassA is a base class of ClassB.
ClassA has no default constructor, but only parameterized constructor.ClassB has a default constructor.
Observations:
- it will not allow creating ClassA without a default constructor
- it will not allow creating ClassA without a default constructor
- if you want to do so, you need to call a base class constructor from ClassB's constructor:
For example, following is the constructor of class A
public ClassA(string someVariable) { ..... some code .... }
To allow ClassA without a default constructor, its all child classes should call base class constructor as below:
public ClassB(): base("some value")
or
public ClassB(string fullName): base(fullName)
No comments:
Post a Comment
Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.
Thanks
Nirman