Книга: C# 2008 Programmer
Inheritance and Constructors
Inheritance and Constructors
Consider the following BaseClass
definition consisting of one default constructor:
public class BaseClass {
//---default constructor---
public BaseClass() {
Console.WriteLine("Constructor in BaseClass");
}
}
Anther class, DerivedClass
inheriting from the BaseClass
, also has a default constructor:
public class DerivedClass : BaseClass {
//---default constructor---
public DerivedClass() {
Console.WriteLine("Constructor in DerivedClass");
}
}
So when an object of DerivedClass
is instantiated, which constructor will be invoked first? The following statement shows that the constructor in the base class will be invoked before the constructor in the current class will be invoked:
DerivedClass dc = new DerivedClass();
The outputs are:
Constructor in BaseClass
Constructor in DerivedClass
What happens if there is no default constructor in the base class, but perhaps a parameterized constructor like the following?
public class BaseClass {
//---constructor---
public BaseClass(int x) {
Console.WriteLine("Constructor in BaseClass");
}
}
In that case, the compiler will complain that BaseClass
does not contain a default constructor.
Remember that if a base class contains constructors, one of them must be a default constructor.
- Chapter 6 Inheritance
- Implementation Inheritance
- Разработка приложений баз данных InterBase на Borland Delphi
- Open Source Insight and Discussion
- Introduction to Microprocessors and Microcontrollers
- Chapter 6. Traversing of tables and chains
- Chapter 8. Saving and restoring large rule-sets
- Chapter 11. Iptables targets and jumps
- Chapter 5 Installing and Configuring VirtualCenter 2.0
- Chapter 16. Commercial products based on Linux, iptables and netfilter
- Appendix A. Detailed explanations of special commands
- Appendix B. Common problems and questions