Книга: 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.

Оглавление книги


Генерация: 2.868. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз