C# Constructors and Inheritance
In this chapter you will learn:
Description
A subclass must declare its own constructors.
Subclass must redefine any constructors it wants to expose.
It can call any of the base class's constructors with the base keyword.
For example,
// w w w . j a v a2s. co m
public class Baseclass
{
public int X;
public Baseclass () { }
public Baseclass (int x) { this.X = x; }
}
public class Subclass : Baseclass
{
public Subclass (int x) : base (x) { }
}
Note
The base keyword works rather like the this keyword, except that it calls a constructor in the base class.
Base class constructors always execute first; this ensures that base initialization occurs before specialized initialization.
For Implicit calling of the parameterless base class constructor. If a constructor in a subclass omits the base keyword, the base type's parameter-less constructor is implicitly called:
public class BaseClass
{//from w w w . jav a 2 s . c o m
public int X;
public BaseClass() { X = 1; }
}
public class Subclass : BaseClass
{
public Subclass() { Console.WriteLine (X); } // 1
}
If the base class has no parameterless constructor, subclasses are forced to use the base keyword in their constructors.
Next chapter...
What you will learn in the next chapter:
- What are destructors
- Syntax for C# Destructor
- Example for C# Destructor
- Destructor calling sequence
- Update static field in the deconstructor
- How to Base destructor got called from child destructor
C# Default constructors
C# Constructor's Parameters
C# Constructor Overload
C# Static Constructors