A constructor of a base class is called before a constructor of a derived class is executed. For example, if Mammal
extends Animal
, then the code contained in the constructor of Animal
is called first when creating an instance of a Mammal
.
If a derived class doesn't explicitly specify which constructor of the base class should be called, the compiler assumes the parameterless constructor.
public class Animal
{
public Animal() { Console.WriteLine("An unknown animal gets born."); }
public Animal(string name) { Console.WriteLine(name + " gets born"); }
}
public class Mammal : Animal
{
public Mammal(string name)
{
Console.WriteLine(name + " is a mammal.");
}
}
In this case, instantiating a Mammal
by calling new Mammal("George the Cat")
will print
An unknown animal gets born.
George the Cat is a mammal.
Calling a different constructor of the base class is done by placing : base(args)
between the constructor's signature and its body:
public class Mammal : Animal
{
public Mammal(string name) : base(name)
{
Console.WriteLine(name + " is a mammal.");
}
}
Calling new Mammal("George the Cat")
will now print:
George the Cat gets born.
George the Cat is a mammal.