Consider we have a class Animal
which has a child class Dog
class Animal
{
public Animal()
{
Console.WriteLine("In Animal's constructor");
}
}
class Dog : Animal
{
public Dog()
{
Console.WriteLine("In Dog's constructor");
}
}
By default every class implicitly inherits the Object
class.
This is same as the above code.
class Animal : Object
{
public Animal()
{
Console.WriteLine("In Animal's constructor");
}
}
When creating an instance of Dog
class, the base classes’s default constructor (without parameters) will be called if there is no explicit call to another constructor in the parent class. In our case, first will be called Object's
constructor, then Animal's
and at the end Dog's
constructor.
public class Program
{
public static void Main()
{
Dog dog = new Dog();
}
}
Output will be
In Animal’s constructor
In Dog’s constructor
Call parent’s constructor explicitly.
In the above examples, our Dog
class constructor calls the default constructor of the Animal
class. If you want, you can specify which constructor should be called: it is possible to call any constructor which is defined in the parent class.
Consider we have these two classes.
class Animal
{
protected string name;
public Animal()
{
Console.WriteLine("Animal's default constructor");
}
public Animal(string name)
{
this.name = name;
Console.WriteLine("Animal's constructor with 1 parameter");
Console.WriteLine(this.name);
}
}
class Dog : Animal
{
public Dog() : base()
{
Console.WriteLine("Dog's default constructor");
}
public Dog(string name) : base(name)
{
Console.WriteLine("Dog's constructor with 1 parameter");
Console.WriteLine(this.name);
}
}
What is going here?
We have 2 constructors in each class.
What does base
mean?
base
is a reference to the parent class. In our case, when we create an instance of Dog
class like this